Chrome浏览器自定义下载目录的等效Selenium代码如何编写?
Chrome 浏览器没有单独的 ChromeProfile 配置类,相关自定义参数统一通过 ChromeOptions 类配置即可,实现下载文件到指定 dest_dir1 目录的等效代码如下:
from selenium import webdriver # 定义Chrome配置对象 chrome_options = webdriver.ChromeOptions() # 配置下载相关参数 download_prefs = { # 指定自定义下载目录,和Firefox配置中的dest_dir1变量通用 "download.default_directory": dest_dir1, # 关闭下载前的弹窗确认 "download.prompt_for_download": False, # 禁用浏览器安全拦截,避免自动下载被阻断 "safebrowsing.enabled": False } # 注入配置参数 chrome_options.add_experimental_option("prefs", download_prefs) # 初始化Chrome驱动 # Selenium 3.x 写法 driver = webdriver.Chrome(executable_path="chromedriver.exe", options=chrome_options) # 如果你使用的是Selenium 4.x 版本,官方推荐用Service类传入驱动路径,写法如下: # from selenium.webdriver.chrome.service import Service # service = Service(executable_path="chromedriver.exe") # driver = webdriver.Chrome(service=service, options=chrome_options)
额外说明:
- 如果需要实现批量文件自动下载,避免浏览器弹出多文件下载授权提示,可以在
download_prefs中新增配置项"profile.content_settings.exceptions.automatic_downloads.*.setting": 1 - 如果有指定MIME类型自动下载的需求,无需额外配置,Chrome会默认信任代码触发的下载行为,无需和Firefox一样单独配置
browser.helperApps.neverAsk.saveToDisk参数
内容的提问来源于stack exchange,提问作者Rikky Bhai
相关产品推荐
相关产品推荐

