最近做一个爬虫项目,是通过selenium模拟浏览器进行爬取的,当启用chromedriver无头模式时就会无法正常访问,按照网上的方法隐藏了一些chromedriver的特征码还是无法访问。
通过网上资料发现,实际上Selenium 启动的浏览器,有几十个特征可以被网站通过 JavaScript 探测到。可以通过访问https://bot.sannysoft.com/进行测试。
正常通过浏览器访问该网站,结果如图:
通过Selenium Chromedriver 无头模式(--headless)打开该网站,结果如图:
在Chromedriver的headless模式下面,如何才能全部隐藏这些特征呢?
我在网上找到了一个stealth.min.js文件可以隐藏这些特征,这个文件的生成方式可以参考,github地址是https://github.com/berstend/puppeteer-extra/tree/master/packages/extract-stealth-evasions
具体的使用方法如下:
# -*- coding: utf-8 -*- """ :author: 阿汤博客 :Description: selenium chromedriver 特征码隐藏 :CreateTime: 2022-05-10 17:02:05 """ import time from selenium.webdriver import Chrome from selenium.webdriver.chrome.options import Options chrome = Options() chrome.add_argument('--headless') chrome.add_argument('user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36') chrome.add_argument('--disable-gpu') chrome.add_argument('--no-sandbox') browser = Chrome(options=chrome) with open('./stealth.min.js') as f: js = f.read() browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", { "source": js }) browser.get('https://bot.sannysoft.com/') time.sleep(1) # 保存为图片 browser.save_screenshot('atang.png') # 可以保存源代码为 html 再双击打开,查看完整结果 source = browser.page_source with open('atang.html', 'w') as f: f.write(source)
运行代码查看atang.png:
再查看atang.html文件:
发现和我们通过浏览器访问https://bot.sannysoft.com/结果一致了。
如果觉得stealth.min.js文件自己生成麻烦,可以直接访问我的网盘获取,我已经生成好了。
2022年9月19日 下午6:02 沙发
看看怎么搞
2022年9月21日 下午5:18 板凳
多谢博主
2022年10月20日 上午10:11 地板
谢谢分享!!!!
2022年12月16日 下午5:25 4楼
看看
2022年12月20日 下午6:38 5楼
非常不错
2022年12月20日 下午6:40 6楼
看看怎么用
2022年12月30日 下午3:04 7楼
漂亮
2023年1月4日 下午4:17 8楼
多谢博主
2023年1月13日 下午2:12 9楼
厉害
2023年2月13日 下午5:28 10楼
非常不错
2023年2月18日 上午11:03 11楼
可以很详细
2023年2月18日 上午11:19 12楼
感谢
2023年3月24日 下午3:23 13楼
赞
2023年3月24日 下午3:24 14楼
赞赞赞
2023年3月24日 下午3:25 15楼
多谢博主
2023年5月10日 上午10:25 16楼
看看
2023年5月10日 上午10:26 17楼
看看看
2023年5月15日 上午10:34 18楼
赞
2023年6月1日 下午7:57 19楼
感谢分享
2023年6月8日 下午8:43 20楼
谢谢
2023年6月16日 下午2:30 21楼
牛的
2023年7月4日 下午12:06 22楼
new牛
2023年7月25日 下午4:52 23楼
哦豁
2023年8月25日 下午10:38 24楼
看起来不错
2023年9月3日 上午6:34 25楼
多谢博主
2023年9月14日 上午8:38 26楼
下载看看
2023年10月14日 上午9:39 27楼
多谢
2023年10月16日 下午9:21 28楼
牛
2023年10月16日 下午9:22 29楼
阿萨
2023年10月18日 下午11:11 30楼
多谢博主
2023年10月18日 下午11:13 31楼
多谢博主“
2023年12月9日 上午10:33 32楼
2023年12月9日 上午10:40 33楼
怎么下载呢
2023年12月16日 下午12:14 34楼
学习 看下行不行
2023年12月16日 下午12:18 35楼
提取码在哪里 怎么看不到啊
2024年1月20日 下午9:05 36楼
nb 无敌
2024年2月6日 下午6:40 37楼
多谢
2024年3月10日 下午8:03 38楼
感谢楼主
2024年3月10日 下午8:04 39楼
谢谢楼主分享
2024年6月3日 下午7:59 40楼
厉害
2024年6月3日 下午8:00 41楼
所以密码是啥
2025年3月4日 下午4:53 42楼
好用吗