0

我正在尝试使用 Selenium(Chrome 驱动程序)下载文件。我使用了一个包含要下载的小示例音频文件的测试网站。该脚本在有头模式下使用时工作正常,文件下载但在无头模式下失败。我查看了一些相关问题,并确保我使用了所有提到的 Chrome 驱动程序选项,但多次弹出以下错误

我也尝试了这里提到的答案,但没有奏效

[0125/104422.896:INFO:CONSOLE(0)] "Refused to execute script from 'https://filesamples.com/detroitchicago/anaheim.js?gcb=2&cb=1' because its MIME type ('image/gif') is not executable.", source: https://filesamples.com/formats/mp3 (0)

我的代码如下

download_dir = "path/to/downloads/"
driver_path = "path/to/driver"

chrome_options = Options()

chrome_options.add_experimental_option("prefs", {"download.default_directory": download_dir,
"download.prompt_for_download": False,
})

chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=1920,1080")
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36")

driver = webdriver.Chrome(executable_path=driver_path,chrome_options=chrome_options)
driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_dir}}
command_result = driver.execute("send_command", params)

base_url = "https://filesamples.com/formats/mp3"
driver.get(base_url)
xpath = "/html/body/div[1]/main/div[2]/div[1]/a"
driver.find_elements_by_xpath(xpath)[0].click()

没有适当的回溯,但我相当有信心该错误是由于该driver.get()方法,因为注释掉该行并没有产生它

Chrome 版本 - 87.0.4280.141
Chrome 驱动程序版本 - 87.0.4280.88

任何帮助,将不胜感激。谢谢!

4

1 回答 1

0
options.add_argument("--headless")
options.add_argument("--window-size=1920, 1080")
options.add_argument(
    "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36")

driver = webdriver.Chrome(options=options)

你也应该设置窗口大小

于 2021-01-26T06:45:09.220 回答