playwright处理下载对话框
时间: 2025-01-07 20:06:45 浏览: 3
### 使用 Playwright 处理下载对话框
为了处理文件下载,Playwright 提供了一套专门用于管理下载事件的 API。通过监听 `download` 事件可以捕获并处理浏览器中的下载操作[^1]。
下面是一个完整的 Python 脚本示例,展示了如何配置页面以自动触发下载,并获取已保存到本地磁盘上的文件路径:
```python
import asyncio
from playwright.async_api import async_playwright
async def run(playwright):
browser = await playwright.chromium.launch(headless=False)
context = await browser.new_context()
page = await context.new_page()
# 设置下载路径
user_data_dir = "/path/to/download/directory"
await context.set_default_navigation_timeout(60000)
# 开始跟踪下载事件
download_path = []
def handle_download(download):
path = download.path()
download_path.append(path)
print(f"Downloaded file saved at {path}")
context.on("download", handle_download)
# 导航至目标网页并点击引发下载行为的按钮或链接
await page.goto('https://example.com')
await page.click('text=Click here to Download')
# 等待一段时间确保下载完成
await asyncio.sleep(5)
# 打印最终下载位置
if len(download_path) > 0:
print(f"The downloaded file is located at: {download_path[-1]}")
await browser.close()
async def main():
async with async_playwright() as pw:
await run(pw)
# 运行异步函数
if __name__ == "__main__":
asyncio.run(main())
```
此脚本创建了一个新的浏览器实例,在访问指定 URL 后模拟用户交互来启动文件下载过程。当检测到有新文件被下载时,会调用回调函数记录其存储地址。最后关闭浏览器结束整个流程。
阅读全文