使用selenium框架的Python爬虫被检测到的 解决方法

2022-10-08,,,,

本人之前在做x宝,x评,x团的爬虫项目时,均遇到了获取cookies这个重要的问题,而获取cookies的前提是实现用户登录,登陆的过程就不赘述了,相信大家都遇到了滑块,滚动条等反爬手段,(本人用webdriver破解),可大厂的技术团队还是给了我们一个更难解决的问题,就是通过js给webdriver请求响应错误信息。那我们的思考路线就是如何让这个js文件功能作废,本人使用的方法是通过 mitmproxy 蔽掉识别 webdriver 标识符的 js 文件。 首先下载mitproxy,pip安装方法:

  pip install mitmproxy

基本使用方法:

给本机设置代理ip 127.0.0.1端口8001(为了让所有流量走mitmproxy)具体方法请百度。

2. 启动mitmproxy。

windows:

mitmdump -p 8001

linux:

mitmproxy -p 8001

3. 打开chrome的开发者工具,找到目标网站是通过哪个js文件控制webdriver相应的, 如:

4. 开始写干扰脚本(driverpass.py):

import re
from mitmproxy import ctx

def response(flow): 
    if '/js/yoda.' in flow.request.url:
        for webdriver_key in ['webdriver', '__driver_evaluate', '__webdriver_evaluate', '__selenium_evaluate', '__fxdriver_evaluate', '__driver_unwrapped', '__webdriver_unwrapped', '__selenium_unwrapped', '__fxdriver_unwrapped', '_selenium_ide_recorder', '_selenium', 'calledselenium', '_webdriver_elem_cache', 'chromedriverw', 'driver-evaluate', 'webdriver-evaluate', 'selenium-evaluate', 'webdrivercommand', 'webdriver-evaluate-response', '__webdriverfunc', '__webdriver_script_fn', '__$webdriverasyncexecutor', '__lastwatiralert', '__lastwatirconfirm', '__lastwatirprompt', '$chrome_asyncscriptinfo', '$cdc_asdjflasutopfhvczlmcfl_' ]:
            ctx.log.info('remove "{}" from {}.'.format(
            webdriver_key, flow.request.url
            ))  
        flow.response.text = flow.response.text.replace('"{}"'.format(webdriver_key), '"no-such-attr"')  
    flow.response.text = flow.response.text.replace('t.webdriver', 'false')
    flow.response.text = flow.response.text.replace('chromedriver', '')

5. 退出刚才的mitmproxy状态,重新用命令行启动mitmproxy干扰脚本 监听8001端口的请求与响应。

mitmdump -s driverpass.py -p 8001

6. 现在别管mitmproxy,启动webdriver 顺利获得cookies。

《使用selenium框架的Python爬虫被检测到的 解决方法.doc》

下载本文的Word格式文档,以方便收藏与打印。