最近做一個爬蟲項目,是通過selenium模擬瀏覽器進(jìn)行爬取的,當(dāng)啟用chromedriver無頭模式時就會無法正常訪問,按照網(wǎng)上的方法隱藏了一些chromedriver的特征碼還是無法訪問。
通過網(wǎng)上資料發(fā)現(xiàn),實際上Selenium 啟動的瀏覽器,有幾十個特征可以被網(wǎng)站通過 JavaScript 探測到??梢酝ㄟ^訪問https://bot.sannysoft.com/進(jìn)行測試。
正常通過瀏覽器訪問該網(wǎng)站,結(jié)果如圖:
通過Selenium Chromedriver 無頭模式(--headless)打開該網(wǎng)站,結(jié)果如圖:
在Chromedriver的headless模式下面,如何才能全部隱藏這些特征呢?
我在網(wǎng)上找到了一個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 再雙擊打開,查看完整結(jié)果 source = browser.page_source with open('atang.html', 'w') as f: f.write(source)
運行代碼查看atang.png:
再查看atang.html文件:
發(fā)現(xiàn)和我們通過瀏覽器訪問https://bot.sannysoft.com/結(jié)果一致了。
如果覺得stealth.min.js文件自己生成麻煩,可以直接訪問我的網(wǎng)盤獲取,我已經(jīng)生成好了。
2022年9月19日 下午6:02 沙發(fā)
看看怎么搞
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樓
可以很詳細(xì)
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樓
學(xué)習(xí) 看下行不行
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樓
好用嗎