Selenium规避网站监测


现在不少大网站有对selenium采取了监测机制。比如正常情况下我们用浏览器访问淘宝等网站的 window.navigator.webdriver的值为 undefined。而使用selenium访问则该值为true。那么如何解决这个问题呢?

只需要设置Chromedriver的启动参数即可解决问题。在启动Chromedriver之前,为Chrome开启实验性功能参数excludeSwitches,它的值为['enable-automation'],完整代码如下:

import time
from selenium import webdriver
from selenium.webdriver import ChromeOptions  # 需要导入的类

# 创建 option 对象
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])

# 创建浏览器对象
driver = webdriver.Chrome(options=option)
driver.implicitly_wait(10)


driver.get('https://www.taobao.com/')
print(driver.title)  # 淘宝网 - 淘!我喜欢

time.sleep(2)
driver.quit()

示例2(带无头的):

import time
from selenium import webdriver
from selenium.webdriver import ChromeOptions  # 需要导入的类

from selenium.webdriver.chrome.options import Options

# 创建一个参数对象,用来控制chrome以无界面模式打开
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
# 创建浏览器对象
# driver = webdriver.Chrome(chrome_options=chrome_options)

# 创建 option 对象
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])

# 创建浏览器对象
driver = webdriver.Chrome(options=option, chrome_options=chrome_options)
driver.implicitly_wait(10)

driver.get('https://www.taobao.com/')
print(driver.title)  # 淘宝网 - 淘!我喜欢

time.sleep(2)
driver.quit()
Python Code


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM