使用Selenium python下载chrome的pdf文件

时间:2018-11-08 15:26:38

标签: python selenium google-chrome pdf download

我正在尝试使用selenium和python下载chrome上的pdf。 一种方法是打开chrome中的设置。

Setting window image

我尝试在使用硒的代码开头做到这一点

driver.get('chrome://settings/content/pdfDocuments')
time.sleep(5)
driver.find_element_by_id('bar').click()

但是总是出错。同样,如果我尝试与该窗口中的所有内容进行互动

Traceback (most recent call last):
File "test_selenium.py", line 37, in <module>
driver.find_element_by_id('knob').click()
File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 360, in find_element_by_id
return self.find_element(by=By.ID, value=id_)
File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
'value': value})['value']
File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"bar"}
(Session info: chrome=70.0.3538.77)
(Driver info: chromedriver=2.40,platform=Linux 4.18.10-100.fc27.x86_64 x86_64)

感谢帮助

1 个答案:

答案 0 :(得分:0)

使用以下命令从npm安装chrome-printtopdf

pip install chrome-printtopdf

使用以下代码下载pdf文件。

from chrome_printtopdf import get_pdf_with_chrome_sync

pdf_file = get_pdf_with_chrome_sync('http://example.org',
chrome_binary='/path/to/chrome-bin')

with open('example.org.pdf', 'wb') as f:
f.write(pdf_file.read())

下面将介绍命令行用法

python -m chrome_printtopdf /path/to/chrome-bin http://example.org/ out.pdf