Selenium-Selenium配置无头浏览器+规避检测

一、谷歌无头浏览器

image

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

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

# 创建浏览器对象
browser = webdriver.Chrome(chrome_options=chrome_options)

# 访问测试
browser.get('https://www.baidu.com')
print(browser.page_source)

二、Selenium规避检测

  • 现在不少网站有对 Selenium采取了检测机制,比如正常情况下我们用浏览器访问某宝的 windows.navigator.webdirver 的值为 undefind,而使用 selenium访问的值为true,那么如何规避呢?
  • 只需要奢侈 Chromedriver的启动参数即可。在启动Chromedriver之前,将Chrom开启验证性功能参数 excludeSwitches,它的值为 ['enable-automation']

image

from selenium import webdriver
# 实现无可视化界面
from selenium.webdriver.chrome.options import Options
# 实现规避检测
from selenium.webdriver import ChromeOptions

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

# 创建浏览器对象,并实现让selenium 规避检测
option = ChromeOptions()
option.add_experimental_option('excludeSwitched', ['enable-automaytion'])

browser = webdriver.Chrome(chrome_options=chrome_options, options=option)

# 访问测试
browser.get('https://www.baidu.com')
print(browser.page_source)
posted @ 2021-05-23 10:45  SRE运维充电站  阅读(1139)  评论(0编辑  收藏  举报