我想下载一个文件,并且可以使用下面的代码来完成。当我将选项传递给驱动程序时,下载不会开始。
from selenium import webdriver
url = "http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/CCARCS-RIACC/DDZip.aspx"
driver.get(url)
driver.find_element_by_id("btnDownload").click()
我尝试传递以下选项,但下载未开始:
from selenium import webdriver
url = "http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/CCARCS-RIACC/DDZip.aspx"
options = webdriver.ChromeOptions()
options.add_argument("download.default_directory=H:/")
options.add_argument('headless')
options.add_argument('window-size=1920x1080')
options.add_argument("disable-gpu")
with webdriver.Chrome(chrome_options=options) as driver:
driver.get(url)
driver.find_element_by_id("btnDownload").click()
我也尝试过:
from selenium import webdriver
url = "http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/CCARCS-RIACC/DDZip.aspx"
with webdriver.Chrome() as driver:
prefs = {
"download.default_directory": down_dir,
"download.prompt_for_download": False,
"download.directory_upgrade": True
}
options.add_experimental_option('prefs', prefs)
driver.get(url)
driver.find_element_by_id("btnDownload").click()
我想用隐藏的浏览器窗口下载文件。另外,是否有一种方法可以在成功下载(使用driver.quit()
)之后立即将其关闭?
编辑:
我删除了重复的驱动程序实例-复制代码段时犯的错误。
答案 0 :(得分:0)
您两次实例化您的webdriver,删除/注释另一行:
with webdriver.Chrome(options=options) as driver:
# driver = webdriver.Chrome(options=options)
也不确定Options类,我相信您应该使用以下命令导入它:
from selenium.webdriver.chrome.options import Options
编辑:是的,Chrome浏览器不会以无头模式下载:SO answer。
因此,为您提供的解决方案是:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
url = "http://wwwapps.tc.gc.ca/Saf-Sec-Sur/2/CCARCS-RIACC/DDZip.aspx"
def enable_download_in_headless_chrome(driver, download_dir):
# add missing support for chrome "send_command" to selenium webdriver
driver.command_executor._commands["send_command"] = ("POST", '/session/$sessionId/chromium/send_command')
params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': download_dir}}
driver.execute("send_command", params)
options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)
enable_download_in_headless_chrome(driver, "H:/")
driver.get(url)
driver.find_element_by_id("btnDownload").click()