【问题标题】:Chrome/Firefox opens PDF in new tab and does not save it in headless mode (Selenium+Python)Chrome/Firefox 在新选项卡中打开 PDF 并且不以无头模式保存 (Selenium+Python)
【发布时间】:2019-10-16 07:38:26
【问题描述】:

我在执行测试时遇到了 headless chrome 问题:单击按钮时 PDF 文件会在新选项卡中打开。如果我在非无头模式下运行测试,一切都很好。但是当尝试在 headless 中做同样的事情时 - 文件没有下载。

options = ChromeOptions()
            options.add_argument('--no-sandbox')
            options.add_argument('--kiosk-printing')
            options.add_argument('--test-type')
            options.add_argument('--disable-infobars')
            options.add_argument('disable-gpu')
            options.add_argument('--verbose')
            options.add_argument('--disable-extensions')
            options.add_argument('--ignore-certificate-errors')
            options.add_experimental_option("prefs", {
                "profile.default_content_settings.popups": 0,
                "download.default_directory": dwnld_path,
                "download.prompt_for_download": False,
                "download.directory_upgrade": True,
                "safebrowsing.enabled": False,
                "plugins.always_open_pdf_externally": True,
                "plugins.plugins_disabled": ["Chrome PDF Viewer"]
            })

我还发现:

wd.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')

params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': dwnld_path}}
        command_result = wd.execute("send_command", params)

但只有当我收到以无头模式下载的请求时才会有帮助,而不是在文件在浏览器中打开时。

【问题讨论】:

    标签: python selenium google-chrome firefox selenium-webdriver


    【解决方案1】:

    尝试保存PDF文件的url并使用请求库下载它,我认为它会工作。

    像这样:

    import urllib3
    import PyPDF2
    import certifi
    import io
    
    http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
    pdf_url = "http:\\XXXXXX.pdf"
    r3 = http.request('GET', pdf_url)
    with io.BytesIO(r3.data) as open_pdf_file:
          read_pdf = PyPDF2.PdfFileReader(open_pdf_file)
          num_pages = read_pdf.getNumPages()
    

    然后我们需要代码的第二部分,你需要以类似的方式保存 pdf

    【讨论】:

    • 不幸的是,JS没有显示=\文件,当我尝试使用wget或urllib从URL获取文件或请求它下载带有JS示例的HTML源代码时:我的url是@987654321 @ 页面源代码包含 blablabla 如果我按 ctrl+s 它会下载文件 file_name.pdf。如果我使用 wget,urllib,请求它下载源代码。所以,我需要一种 ctrl+s 模拟......而且我宁愿不使用 ActionChains......它太“ducktapely”(=
    • Nono,没有 html 文件,只需从 html 中获取 pdf_url,请参阅我上面编辑的评论。
    • read_pdf = PyPDF2.PdfFileReader(open_pdf_file) 我得到一个错误:PyPDF2.utils.PdfReadError: EOF marker not found
    猜你喜欢
    • 2016-09-02
    • 2012-04-25
    • 1970-01-01
    • 2019-08-04
    • 2018-11-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 2017-09-24
    相关资源
    最近更新 更多