selenium如何指定下载目录?

代码:
from selenium import webdriver # 导入webdriver


def get_driver():
    options = webdriver.ChromeOptions()  # 设置谷歌浏览器的一些配置选项
    options.add_argument('--window-size=1920,1800')  # 指定浏览器分辨率
    options.add_argument('--incognito')  # 隐身模式(无痕模式)
    options.add_argument('--headless')  # 无头模式
    # options.add_argument('lang=zh_CN.UTF-8')  # 设置编码格式
    options.add_argument('--hide-scrollbars')  # 隐藏滚动条, 应对一些特殊页面
    # 屏蔽谷歌浏览器正在接收自动化软件控制提示,加上以下两行
    options.add_experimental_option('useAutomationExtension', False)
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    options.add_argument("disable-blink-features=AutomationControlled")  # 去掉webdriver痕迹
    options.add_argument('--disable-gpu')  # 规避bug
    options.add_argument('--no-sandbox')  # 取消沙盒模式,解决DevToolsActivePort文件不存在的报错
    options.add_argument('--disable-dev-shm-usage')  # 克服有限的资源问题
    options.add_argument('blink-settings=imagesEnabled=false')  # 不加载图片, 提升速度
    prefs = {"credentials_enable_service": False, "profile.password_manager_enabled": False}  # 登录时关闭弹出的密码保存提示框
    prefs.update({'profile.default_content_setting_values': {'notifications': 2}})  # 禁用浏览器弹窗
    prefs.update({'download.prompt_for_download': False, 'download.default_directory': '设置下载的具体目录'})  # 设置默认下载地址
    options.add_experimental_option('prefs', prefs)
    driver = webdriver.Chrome(executable_path='chrmedriver所在路径', options=options)
    # 规避webdriver检测
    driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
        "source": """
                   Object.defineProperty(navigator,'webdriver',{
                       get: () => undefined
                   })
               """
    })
    return driver

 

posted @ 2022-05-12 13:48  eliwang  阅读(1068)  评论(0编辑  收藏  举报