selenium用无头模式下载csv文件,它无效

时间:2018-06-04 03:13:24

标签: python-2.7 selenium google-chrome-headless

我使用selenium下载csv文件。 (网址类似于https://hogehoge_YYYYMMDD.csv

使用--headless选项时,它无效。但是没有添加无头选项,它是有效的!

有什么想法吗?

感谢您的帮助。

硒(3.10.0)
Python(2.7.10)
Chrome(66.0.3359.181)我还尝试了最新的Chrome版本67.0.3396.62。但同样的结果发生了。

options = Options()
# if comment out this sentence, I can get csv file.
# options.add_argument('--headless')

options.add_argument("--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36")
options.add_argument('--window-size=1280,1024')
options.add_experimental_option("prefs", {
  "download.default_directory":DIR_NAME,
})


driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver',chrome_options=options)

driver.set_window_size(1280, 720) 

print URL
print "loading url"
driver.get(URL)
print "load end"

1 个答案:

答案 0 :(得分:3)

这是答案。 https://bugs.chromium.org/p/chromium/issues/detail?id=696481#c86

我修复了我的代码。以下是。

def enable_download_in_headless_chrome(browser, download_dir):
    #add missing support for chrome "send_command"  to selenium webdriver
    browser.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')

    params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_dir}}
    browser.execute("send_command", params)

options = Options()
options.add_argument('--headless')

options.add_argument("--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36")
options.add_argument('--window-size=1280,1024')
# options.add_experimental_option("prefs", {
#   "download.default_directory":DIR_NAME,
# })


driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver',chrome_options=options)

driver.set_window_size(1280, 720) 


enable_download_in_headless_chrome(driver, DIR_NAME)

print URL
print "loading url"
driver.get(URL)
print "load end"