selenium to download csv file with headless mode, it is not working

两盒软妹~` 提交于 2020-04-30 04:32:21

问题


I download csv file by using selenium. (URL is like https://hogehoge_YYYYMMDD.csv )

With using --headless option, it's not working. But not adding headless option, it is worked!

Any idea?

Thanks for your help.

selenium (3.10.0)
Python (2.7.10)
Chrome (66.0.3359.181) I also tried latest Chrome version 67.0.3396.62. But same result happens.

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:


Here is the answer. https://bugs.chromium.org/p/chromium/issues/detail?id=696481#c86

I fixed my code. Here is the below.

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"


来源:https://stackoverflow.com/questions/50673006/selenium-to-download-csv-file-with-headless-mode-it-is-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!