【问题标题】:Selenium Firefox browser is stuck after downloading pdfSelenium Firefox 浏览器在下载 pdf 后卡住
【发布时间】:2020-11-20 21:15:39
【问题描述】:

希望有人可以帮助我了解发生了什么:

我正在使用 Selenium 和 Firefox 浏览器下载 pdf(需要 Selenium 登录到相应的网站):

    le = browser.find_elements_by_xpath('//*[@title="Download PDF"]')
    time.sleep(5)
    if le:
        pdf_link = le[0].get_attribute("href")
        browser.get(pdf_link)

代码确实会下载 pdf,但之后就一直处于空闲状态。 这似乎与以下浏览器设置有关:

   fp.set_preference("pdfjs.disabled", True)
   fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "application/pdf")

如果我禁用第一个,它不会挂起,而是打开 pdf 而不是下载它。如果我禁用第二个,则会出现一个“另存为”弹出窗口。有人能解释一下如何处理吗?

【问题讨论】:

  • 如果您找到了解决方案,请分享!我有同样的问题!谢谢:)
  • @jonesy 我已经设法让它与“le[0].click()”一起工作,但是有很多页面特定的 JS 东西。

标签: python selenium


【解决方案1】:

对我来说,解决这个问题的最好方法是让 Firefox 通过 pdf.js 在浏览器中呈现 PDF,然后通过 Python 请求库发送后续获取,并附加 selenium cookie。更多解释如下:

有几种方法可以通过 Firefox + Selenium 呈现 PDF。如果您使用的是最新版本的 Firefox,它很可能会通过 pdf.js 呈现 PDF,以便您可以内联查看。这并不理想,因为现在我们无法下载文件。

您可以通过 Selenium 选项 disable pdf.js 但这可能会导致浏览器卡住的问题。这可能是因为未知的 MIME 类型,但我不完全确定。 (another StackOverflow answer 表示这也是 Firefox 版本的原因。)

但是,我们可以通过passing Selenium's cookie session 绕过这个到requests.session()

这是一个玩具示例:

import requests
from selenium import webdriver

pdf_url = "/url/to/some/file.pdf"

# setup driver with options
driver = webdriver.Firefox(..options)

# do whatever you need to do to auth/login/click/etc.

# navigate to the PDF URL in case the PDF link issues a 
# redirect because requests.session() does not persist cookies
driver.get(pdf_url)

# get the URL from Selenium 
current_pdf_url = driver.current_url

# create a requests session
session = requests.session()

# add Selenium's cookies to requests
selenium_cookies = driver.get_cookies()
for cookie in selenium_cookies:
    session.cookies.set(cookie["name"], cookie["value"])

# Note: If headers are also important, you'll need to use 
# something like seleniumwire to get the headers from Selenium 

# Finally, re-send the request with requests.session
pdf_response = session.get(current_pdf_url)

# access the bytes response from the session
pdf_bytes = pdf_response.content

我强烈建议使用 seleniumwire 而不是常规 selenium,因为它扩展了 Python Selenium 以允许您返回标头、等待请求完成、使用代理等等。

【讨论】:

    猜你喜欢
    • 2022-10-18
    • 2018-12-11
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多