簡體   English   中英

Chrome / Firefox在新標簽頁中打開PDF,並且不會以無頭模式保存它(Selenium + Python)

[英]Chrome/Firefox opens PDF in new tab and does not save it in headless mode (Selenium+Python)

我在執行測試時遇到無頭鉻的問題:單擊按鈕時,PDF文件在新選項卡中打開。 如果我在NON-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)

但這僅在我收到以無頭模式下載的請求時才有幫助,而在文件在瀏覽器中打開時則無濟於事。

嘗試保存PDF文件的網址,然后將其與請求庫一起下載,我認為它會起作用。

像這樣:

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的代碼的第二部分

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM