当前位置:   article > 正文

undetected_chromedriver解决网页被检测(转载)_undetected chrome driver

undetected chrome driver

一、问题分析

selenium打开浏览器模仿人工操作是诸多爬虫工作者最万能的网页数据获取方式,但是在做自动化爬虫时,经常被检测到是selenium驱动。比如前段时间selenium打开维普高级搜索时得到的页面是空白页,懂车帝对selenium反爬也很厉害。

二、Selenium为何会被检测

    主要原因是selenium打开的浏览器指纹和人工操作打开的浏览器指纹是不同的,比如最熟知的window.navigator.webdriver关键字,在selenium打开的浏览器打印返回结果为true,而正常浏览器打印结果返回为undefined,我们可以在(https://bot.sannysoft.com/)网站比较各关键字。

三、Selenium防检测方法
1. 修改window.navigator.webdriver关键字返回结果

  1. from selenium import webdriver
  2. options = webdriver.ChromeOptions()
  3. # 此步骤很重要,设置为开发者模式,防止被各大网站识别出来使用了Selenium
  4. driver = webdriver.Chrome(options=options)
  5. driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
  6. "source": """
  7. Object.defineProperty(navigator, 'webdriver', {
  8. get: () => undefined
  9. })
  10. """
  11. })

但是因为浏览器指纹很多,这种方法的局限性是显而易见的。

2. 使用stealth.min.js文件防止selenium被检测

  1. import time
  2. from selenium.webdriver import Chrome
  3. from selenium.webdriver.chrome.options import Options
  4. chrome_options = Options()
  5. chrome_options.add_argument("--headless")
  6. chrome_options.add_argument('user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36')
  7. driver = Chrome('./chromedriver', options=chrome_options)
  8. with open('/Users/kingname/test_pyppeteer/stealth.min.js') as f:
  9. js = f.read()
  10. driver.execute_cdp_cmd("Page.add`在这里插入代码片`ScriptToEvaluateOnNewDocument", {
  11. "source": js
  12. })

stealth.min.js文件来源于puppeteer,有开发者给 puppeteer 写了一套插件,叫做puppeteer-extra。其中,就有一个插件叫做puppeteer-extra-plugin-stealth专门用来让 puppeteer 隐藏模拟浏览器的指纹特征。

python开发者就需要把其中的隐藏特征的脚本提取出来,做成一个 js 文件。然后让 Selenium 或者 Pyppeteer 在打开任意网页之前,先运行一下这个 js 文件里面的内容。

puppeteer-extra-plugin-stealth的作者还写了另外一个工具,叫做extract-stealth-evasions。这个东西就是用来生成stealth.min.js文件的。
三、使用undetected_chromedriver

undetected_chromedriver 可以防止浏览器特征被识别,并且可以根据浏览器版本自动下载驱动。不需要自己去下载对应版本的chromedriver。

  1. import undetected_chromedriver as uc
  2. driver = uc.Chrome()
  3. driver.get('目标网址')

 四、undetected_chromedriver自定义功能

  1. import undetected_chromedriver as uc
  2. #specify chromedriver version to download and patch
  3. #this did not work correctly until 1.2.1
  4. uc.TARGET_VERSION = 78
  5. # or specify your own chromedriver binary to patch
  6. undetected_chromedriver.install(
  7. executable_path='c:/users/user1/chromedriver.exe',
  8. )
  9. from selenium.webdriver import Chrome, ChromeOptions
  10. opts = ChromeOptions()
  11. opts.add_argument(f'--proxy-server=socks5://127.0.0.1:9050')
  12. driver = Chrome(options=opts)
  13. driver.get('目标网址')

有时候会报chrome的版本不匹配,undetected_chromedriver可以根据浏览器版本自动下载驱动,自然不存在版本不匹配问题,最终发现是undetected_chromedriver只支持chrome96及以上的版本,需将chrome浏览器版本升级。
五、undetected-chromedriver 代理插件

  1. import os
  2. import shutil
  3. import tempfile
  4. import undetected_chromedriver as webdriver
  5. class ProxyExtension:
  6. manifest_json = """
  7. {
  8. "version": "1.0.0",
  9. "manifest_version": 2,
  10. "name": "Chrome Proxy",
  11. "permissions": [
  12. "proxy",
  13. "tabs",
  14. "unlimitedStorage",
  15. "storage",
  16. "<all_urls>",
  17. "webRequest",
  18. "webRequestBlocking"
  19. ],
  20. "background": {"scripts": ["background.js"]},
  21. "minimum_chrome_version": "76.0.0"
  22. }
  23. """
  24. background_js = """
  25. var config = {
  26. mode: "fixed_servers",
  27. rules: {
  28. singleProxy: {
  29. scheme: "http",
  30. host: "%s",
  31. port: %d
  32. },
  33. bypassList: ["localhost"]
  34. }
  35. };
  36. chrome.proxy.settings.set({value: config, scope: "regular"}, function() {});
  37. function callbackFn(details) {
  38. return {
  39. authCredentials: {
  40. username: "%s",
  41. password: "%s"
  42. }
  43. };
  44. }
  45. chrome.webRequest.onAuthRequired.addListener(
  46. callbackFn,
  47. { urls: ["<all_urls>"] },
  48. ['blocking']
  49. );
  50. """
  51. def __init__(self, host, port, user, password):
  52. self._dir = os.path.normpath(tempfile.mkdtemp())
  53. manifest_file = os.path.join(self._dir, "manifest.json")
  54. with open(manifest_file, mode="w") as f:
  55. f.write(self.manifest_json)
  56. background_js = self.background_js % (host, port, user, password)
  57. background_file = os.path.join(self._dir, "background.js")
  58. with open(background_file, mode="w") as f:
  59. f.write(background_js)
  60. @property
  61. def directory(self):
  62. return self._dir
  63. def __del__(self):
  64. shutil.rmtree(self._dir)
  65. if __name__ == "__main__":
  66. proxy = ("64.32.16.8", 8080, "username", "password") # your proxy with auth, this one is obviously fake
  67. proxy_extension = ProxyExtension(*proxy)
  68. options = webdriver.ChromeOptions()
  69. options.add_argument(f"--load-extension={proxy_extension.directory}")
  70. driver = webdriver.Chrome(options=options)
  71. driver.get("Just a moment...")
  72. driver.quit()

附带浏览器环境检测网址:https://bot.sannysoft.com/ 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/949283
推荐阅读
相关标签
  

闽ICP备14008679号