You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Playwright Python通过CDP连接调试浏览器下载报表时出现临时文件无法保存的问题求助

Playwright Python通过CDP连接调试浏览器下载报表时出现临时文件无法保存的问题求助

我现在尝试用Playwright结合Python代码来获取一些免费报表。我用了下面的代码,连接已经打开的Chrome调试窗口,但尝试获取报表时,浏览器里出现了一个无法保存的临时文件(类似那种奇怪的文件)。

直接点击下载按钮也不管用,所以我想试试用page.evaluate方法来实现,这是我的代码:

from playwright.sync_api import sync_playwright

def run(playwright):
    browser = playwright.chromium.connect_over_cdp('http://localhost:9222')
    context = browser.contexts[0]
    page = context.pages[0]
    with page.expect_download() as download_info:
        page.evaluate("""
                fetch('https://www.ice.com/marketdata/api/reports/166/download/pdf', {
                    method: 'POST',
                    headers: {
                        'sec-ch-ua-platform': '"Windows"',
                        'referer': 'https://www.ice.com/report/166',
                        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
                        'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
                        'content-type': 'application/x-www-form-urlencoded',
                        'sec-ch-ua-mobile': '?0'
                    },
                    body: new URLSearchParams({
                        'exchangeCodeAndContract': 'IFLX,C',
                        'selectedDate': '2025-01-02'
                    })
                }).then(response => response.blob())
                  .then(blob => {
                      const url = window.URL.createObjectURL(blob);
                      const a = document.createElement('a');
                      a.style.display = 'none';
                      a.href = url;
                      a.download = 'report.pdf';
                      document.body.appendChild(a);
                      a.click();
                      window.URL.revokeObjectURL(url);
                  });
            """)

    download = download_info.value
    download.save_as('test.pdf')

    try:
        while True:
            pass
    except KeyboardInterrupt:
        print("Program terminated by user.")
    finally:
        page.close()
        context.close()
        browser.close()

with sync_playwright() as playwright:
    run(playwright)

有没有什么解决思路?谢谢!
Laurent

备注:内容来源于stack exchange,提问作者Scnes de Ouf

火山引擎 最新活动