
Selenium是一个流行的自动化网页测试工具,可以通过模拟用户在Chrome浏览器中的操作来完成网站的测试。然而,有些网站会检测浏览器是否由Selenium驱动,如果是,就会返回错误的结果或拒绝访问。为了避免这种情况,我们需要隐藏Selenium的特征,让网站认为我们是正常的用户。
以下是三种常见的隐藏Selenium特征的方法:
综上所述,隐藏Selenium特征是实现自动化网页测试的关键。通过以上三种方法,我们可以让浏览器看起来更像正常的用户,避免被网站检测到并拒绝访问。综合上面的几种selenium特征隐藏方式,以采集大众点评的评论为案例,结合实际爬虫采集过程中需要使用的代理IP池,提供如下demo:
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType
# 亿牛云爬虫加强版代理IP 地址、端口号、用户名和密码
proxy_address = 'www.16yun.cn'
proxy_port = '3100'
proxy_username = '16YUN'
proxy_password = '16IP'
# 设置Chrome选项,包括隐藏Selenium特征、设置代理IP和排除或关闭一些Selenium相关开关
options = webdriver.ChromeOptions()
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_argument('--disable-extensions')
options.add_argument('--disable-gpu')
options.add_argument('--disable-infobars')
options.add_argument('--disable-notifications')
options.add_argument('--disable-popup-blocking')
options.add_argument('--disable-web-security')
options.add_argument('--ignore-certificate-errors')
options.add_argument('--no-sandbox')
options.add_argument('--start-maximized')
options.add_argument('--user-data-dir=/dev/null')
options.add_argument('--proxy-server={}'.format(proxy_address + ':' + proxy_port))
options.add_argument('--proxy-auth={}:{}'.format(proxy_username, proxy_password))
options.add_experimental_option('excludeSwitches', ['enable-automation', 'useAutomationExtension'])
# 初始化Chrome浏览器,并使用上述选项
driver = webdriver.Chrome(options=options)
# 隐藏navigator.webdriver标志,将其值修改为false或undefined
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
'source': 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'
})
# 设置user-agent,改变user-agent的值
user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
driver.execute_cdp_cmd("Network.setUserAgentOverride", {"userAgent": user_agent})
# 访问大众点评中商品的评论页面
url = 'https://www.dianping.com/shop/1234567/review_all'
driver.get(url)
# 在此处添加其他代码来执行您想要的任务此代码将使用Chrome浏览器,并在启动浏览器时使用选项隐藏Selenium特征、设置用户名和密码方式的代理IP和排除或关闭一些Selenium相关开关。然后,使用execute_cdp_cmd命令来执行Google Chrome DevTools协议中的命令,将navigator.webdriver标志的值修改为false或undefined。使用execute_cdp_cmd命令来设置Network.setUserAgentOverride参数,将user-agent更改为指定的user-agent字符串。最后,访问大众点评中商品的评论页面,并在此处添加其他代码来执行您想要的任务.
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。