【问题标题】:Using Selenium with Python in Chrome to click "download" button and download PDF在 Chrome 中使用 Selenium 和 Python 单击“下载”按钮并下载 PDF
【发布时间】:2021-02-18 00:28:39
【问题描述】:

我正在尝试从以下网址下载 PDF,https://sec.report/Document/0001670254-20-001152/

在 html 中嵌入了一个下载按钮。我正在使用以下代码单击按钮并将下载内容发送到我的路径中定义的桌面。程序运行没有任何错误,但 PDF 未显示在桌面上。我尝试将位置更改为不同的位置,即下载。我还切换了 google chrome 中的首选项以下载 PDF 文件,而不是在 Chrome 中自动打开它们。有什么想法吗?

from selenium import webdriver

download_dir = "C:\\Users\\andrewlittle\\Desktop" 
options = webdriver.ChromeOptions()

profile = {"plugins.plugins_list": [{"enabled": False, "name": "Chrome PDF Viewer"}], 
               "download.default_directory": download_dir , "download.extensions_to_open": "applications/pdf"}
options.add_experimental_option("prefs", profile)
chromedriver_path = os.getcwd() + '/chromedriver'
driver = webdriver.Chrome(ChromeDriverManager().install())

driver.get('https://sec.report/Document/0001670254-20-001152/document_1.pdf')

driver.close()

提前致谢!

【问题讨论】:

    标签: python pdf path selenium-chromedriver


    【解决方案1】:

    请看下面的答案:

    import time
    from webdriver_manager.chrome import ChromeDriverManager
    from selenium.webdriver.chrome.service import Service
    from selenium.webdriver.chrome.options import Options
    from selenium import webdriver
    
    download_dir = "/Users/test/Documents/"
    
    options = Options()
    options.add_experimental_option('prefs',  {
        "download.default_directory": download_dir,
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "plugins.always_open_pdf_externally": True
        }
    )
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=options)
    
    driver.get('https://sec.report/Document/0001670254-20-001152/document_1.pdf')
    time.sleep(3)
    driver.quit()
    

    为了安全起见,我将 time.sleep 放入其中,以防文件需要更长的时间来下载。但是,这不是必需的。

    我还为 Selenium 使用了较新的 Service 和 Options 对象。

    代码的关键是使用,

        "download.default_directory": download_dir,
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "plugins.always_open_pdf_externally": True
    

    这些允许 Chrome 下载 PDF 而不提示您选择的目录。

    【讨论】:

    • 嗨@Ryan,感谢您的帮助。该代码是有道理的,但是当我运行它时,我得到以下类型错误:__init__() 得到了一个意外的关键字参数“服务”,堆栈跟踪引用了这一行,“服务 = 服务(ChromeDriverManager()。安装())”。我想不出为什么会发生这种情况,有什么想法吗?谢谢!
    • 我能够通过删除服务 = Service(ChromeDriverManager().install()) 并替换为 driver = webdriver.Chrome(ChromeDriverManager().install(), options= 来解决问题选项)。再次感谢您的帮助!
    • @AndrewLittle1 很高兴听到!
    猜你喜欢
    • 2019-05-28
    • 2019-04-12
    • 1970-01-01
    • 2022-01-26
    • 2020-05-04
    • 2021-03-10
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    相关资源
    最近更新 更多