Selenium Webdriver options的实用参数设置

1、关闭Chrome浏览器受自动控制的提示

options.add_experimental_option('useAutomationExtension', False)
options.add_experimental_option('excludeSwitches', ['enable-automation'])

2、关闭是否保存密码的弹窗

options.add_experimental_option("prefs", 
{  "credentials_enable_service": False,
   "profile.password_manager_enabled":False,
})

3、下载文件时自动下载到指定的目录,不要弹出保存文件对话框

options.add_experimental_option("prefs", 
{  "download.default_directory": r'd:\temp', # 设置默认保存文件路径
   "download.prompt_for_download": False,    # 设置保存文件之前是否弹出保存对话框
   "download.directory_upgrade": True,  
})

4、下载文件完成后不要扫描文件,减少等待的时间

options.add_argument('--safebrowsing-disable-download-protection')
options.add_experimental_option("prefs", 
{  "safebrowsing.enabled": False, 
   "download.directory_upgrade": True,  
})

5、关闭是否允许同时下载多个文件的提示

options.add_experimental_option("prefs", 
{  "profile.default_content_settings.popups": 0,
   "profile.default_content_setting_values.automatic_downloads": 1
})

6、跳过网站检测爬虫

driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": "Object.defineProperty(navigator, 'webdriver', {get: () => False}) "})

注意:这一语句是在options.add_argument()语句以及driver = webdriver.Chrome(options=options)后面的。可以有效解决webdriver打开某些网站呈空白页面的问题。

7、强行显示英文版网站

可解决浏览器打开某些国外网站时会自作主张切换到中文版网站的问题(如:某英社交网站)

options.add_experimental_option('prefs', {'intl.accept_languages': 'en,en_US'})

8、设置代理

options.add_argument('--proxy-server=127.0.0.1:8080')

9、手动添加user-agent

可以有效解决无头模式(headless)访问网站的异常情况,可参考我另一篇博文:https://blog.csdn.net/Scott0902/article/details/129384085

user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36'
options.add_argument(f'user-agent={user_agent}')

猜你喜欢

转载自blog.csdn.net/Scott0902/article/details/129405473
今日推荐