如何在Selenium Python中关闭webdriver模式并实现浏览器防检测?
彻底规避Firefox Selenium的webdriver检测
以下是针对Firefox浏览器,彻底关闭webdriver特征、避免被检测的优化方案:
1. 优化后的完整代码配置
在现有代码基础上补充关键隐藏配置,同时通过JS强制覆盖检测属性:
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.53 Safari/537.36' options = webdriver.FirefoxOptions() options.binary_location = r"C:\Program Files\Mozilla Firefox\firefox.exe" # 基础隐藏配置 options.set_preference("general.useragent.override", ua) options.set_preference("dom.webdriver.enabled", False) options.set_preference("useAutomationExtension", False) options.set_preference("devtools.jsonview.enabled", False) # 新增关键特征隐藏配置 options.set_preference("dom.webnotifications.enabled", False) options.set_preference("media.navigator.enabled", False) options.set_preference("browser.cache.disk.enable", False) options.set_preference("browser.cache.memory.enable", False) options.set_preference("extensions.pocket.enabled", False) options.set_preference("browser.sessionstore.resume_from_crash", False) driver = webdriver.Firefox(options=options, executable_path='geckodriver.exe') action=ActionChains(driver) # 强制重写navigator.webdriver属性,彻底屏蔽JS层面检测 driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})") driver.get('https://intoli.com/blog/not-possible-to-block-chrome-headless/chrome-headless-test.html')
2. 核心优化说明
- JS属性重写:部分检测逻辑会直接读取
navigator.webdriver属性,仅通过Firefox偏好设置无法完全屏蔽,需通过执行JS强制覆盖。 - 减少特征差异:关闭通知、媒体设备访问、默认扩展等功能,缩小自动化浏览器与普通用户浏览器的行为差异。
- 清理缓存痕迹:禁用各类浏览器缓存,避免留下自动化访问的残留标识。
3. 额外注意事项
- 确保
geckodriver版本与本地Firefox版本完全匹配,版本不兼容会导致部分配置失效。 - 模拟真实用户行为:添加随机停顿、页面滚动、点击等操作,避免机械性的访问模式。
- 若仍被检测,可尝试搭配代理IP,模拟不同地域的访问来源。
内容的提问来源于stack exchange,提问作者kamazz
相关产品推荐
相关产品推荐

