CDP模式下SeleniumBase触发WEBDRIVER指纹检测失败如何解决?
问题
使用SeleniumBase的CDP模式访问https://antoinevastel.com/bots/时,WEBDRIVER检测项显示红色(未通过),该如何解决?
示例代码:
from seleniumbase import SB with SB(uc=True, locale_code="en", headless=True) as sb: link = "https://antoinevastel.com/bots/" print(f"\nOpening {link}") sb.wait_for_ready_state_complete(timeout=120) sb.activate_cdp_mode(link) print(f"Sleeping for some time...") sb.sleep(5) [screenwidth,screenheight,innerwidth,innerheight,scrollwidth,scrollheight] = sb.cdp.evaluate("return [window.screen.width, window.screen.height, window.innerWidth, window.innerHeight, document.documentElement.scrollWidth, document.documentElement.scrollHeight];") print(f"Size: {screenwidth}, {screenheight}, {innerwidth}, {innerheight}, {scrollwidth}, {scrollheight}") sb.cdp.set_window_rect(0,0,scrollwidth + screenwidth - innerwidth, scrollheight + screenheight - innerheight + 100) print(f"Sleeping for some time...") sb.sleep(5) sb.cdp.save_screenshot(f"screenshot.png") print(f"Finished!")
编辑补充:在SeleniumBase项目的Issue#3059中提到,该检测结果与常规Chrome浏览器一致,WEBDriver值不一致的检测并不准确。
解决方案
- 调整CDP模式激活时机:原代码先加载页面再切换CDP模式,会导致页面初始化时暴露特征。应先激活CDP模式,再注入防检测脚本,最后打开目标链接。
- 手动覆盖
navigator.webdriver属性:通过CDP指令在页面加载前注入脚本,修改该属性的返回值,绕过检测。 - 使用内置窗口调整方法:避免直接调用
cdp.set_window_rect,改用SeleniumBase内置的set_window_size方法,减少异常特征触发。
修改后的完整代码
from seleniumbase import SB with SB(uc=True, locale_code="en", headless=True) as sb: link = "https://antoinevastel.com/bots/" print(f"\nOpening {link}") # 先激活CDP模式并注入防检测脚本 sb.activate_cdp_mode() sb.cdp.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { "source": """ Object.defineProperty(navigator, 'webdriver', { get: () => undefined }) """ }) sb.open(link) sb.wait_for_ready_state_complete(timeout=120) print(f"Sleeping for some time...") sb.sleep(5) size_data = sb.cdp.evaluate("return [window.screen.width, window.screen.height, window.innerWidth, window.innerHeight, document.documentElement.scrollWidth, document.documentElement.scrollHeight];") screenwidth, screenheight, innerwidth, innerheight, scrollwidth, scrollheight = size_data print(f"Size: {screenwidth}, {screenheight}, {innerwidth}, {innerheight}, {scrollwidth}, {scrollheight}") # 使用内置方法设置窗口大小 sb.set_window_size(scrollwidth + screenwidth - innerwidth, scrollheight + screenheight - innerheight + 100) print(f"Sleeping for some time...") sb.sleep(5) sb.cdp.save_screenshot(f"screenshot.png") print(f"Finished!")
额外说明
根据Issue#3059的信息,该检测本身存在准确性问题,即使修改后仍可能显示红色,但此时浏览器环境已与常规Chrome一致,不会被实际的反爬机制拦截。
内容的提问来源于stack exchange,提问作者sudoExclamationExclamation
相关产品推荐
相关产品推荐

