如何在使用undetected_chromedriver时获取Requests?
如何在使用undetected_chromedriver时获取Requests?
我太懂你的处境了——之前用seleniumwire的时候,直接从driver里抓取请求别提多顺手,现在换成undetected_chromedriver躲反爬,却没了这个核心功能,连seleniumwire自带的undetected模式还被验证码盯上,属实头疼。
别担心,有两种靠谱的方法能让你在纯undetected_chromedriver环境下捕获请求,避开被检测的问题:
方法一:利用Chrome DevTools Protocol(CDP)监听请求
undetected_chromedriver本质还是基于ChromeDriver,天然支持调用Chrome的DevTools协议,我们可以用它直接监听浏览器的网络请求。
下面是完整的示例代码:
from time import sleep import undetected_chromedriver as uc def setup_request_capture(driver): # 启用网络监控 driver.execute_cdp_cmd("Network.enable", {}) captured_requests = [] # 定义请求捕获的回调函数 def capture_request(event): # 可以在这里过滤请求,比如只保留GET/POST,或者特定域名的请求 captured_requests.append({ "url": event["request"]["url"], "method": event["request"]["method"], "headers": event["request"]["headers"] }) # 绑定请求监听事件 driver.add_cdp_listener("Network.requestWillBeSent", capture_request) return captured_requests if __name__ == '__main__': driver = uc.Chrome() requests = setup_request_capture(driver) driver.get("https://www.nowsecure.nl") sleep(5) # 打印捕获到的请求详情 print("捕获到的请求列表:") for idx, req in enumerate(requests, 1): print(f"\n请求 {idx}:") print(f"方法: {req['method']}") print(f"URL: {req['url']}") print(f"请求头: {req['headers']}") print("\n页面标题:", driver.title) driver.quit()
如果需要捕获响应内容,只需要再绑定Network.responseReceived事件,就能拿到响应的状态码、响应头,还可以调用Network.getResponseBody获取完整响应内容。
方法二:用中间代理(比如mitmproxy)捕获请求
如果想要更接近seleniumwire的使用体验,可以用一个本地代理来拦截所有浏览器请求,mitmproxy就是个不错的选择——它轻量且功能强大,还能自定义请求处理逻辑。
示例代码如下:
from time import sleep import undetected_chromedriver as uc import threading # mitmproxy的请求处理脚本逻辑 def request(flow): print(f"\n捕获到请求:") print(f"方法: {flow.request.method}") print(f"URL: {flow.request.url}") print(f"请求体: {flow.request.text if flow.request.text else '无'}") # 后台启动mitmproxy def start_proxy(): from mitmproxy.tools.main import mitmdump # 启动代理并加载当前脚本的request函数,监听8080端口 mitmdump(["-s", __file__, "--listen-port", "8080"]) if __name__ == '__main__': # 启动代理线程 proxy_thread = threading.Thread(target=start_proxy, daemon=True) proxy_thread.start() sleep(2) # 等待代理启动完成 # 配置undetected_chromedriver使用代理 options = uc.ChromeOptions() options.add_argument('--proxy-server=http://127.0.0.1:8080') # 注意:第一次使用mitmproxy需要安装证书,否则HTTPS请求会失败 driver = uc.Chrome(options=options) driver.get("https://www.nowsecure.nl") sleep(5) print("\n页面标题:", driver.title) driver.quit()
注意事项
- CDP方法不需要额外安装工具,代码更轻量化,但需要自己处理请求的过滤、存储逻辑;
- mitmproxy方法功能更全面,支持修改请求/响应,但需要先安装
mitmproxy(pip install mitmproxy),并且第一次运行要手动信任mitmproxy的根证书,避免HTTPS请求被拦截; - 两种方法都不会引入
seleniumwire的检测风险,能保持undetected_chromedriver的反爬优势。
备注:内容来源于stack exchange,提问作者fer0m
相关产品推荐
相关产品推荐

