options = ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_experimental_option('useAutomationExtension', False)
ua = '--user-agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) >AppleWebKit/536.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/536.36 Edg/87.0.664.57'
#针对UA请求头的操作,防止因为没有添加请求头导致的访问被栏截了
# options.add_argument('User-Agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) >AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.57')
# options.add_argument('User-Agent=Chrome/87.0.4280.88')
# options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 6.1; Win64; x64) >AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.57')
options.add_argument(ua)
# 下面的过期了
# options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.66 Safari/535.11')
options.add_argument("--user-data-dir=/tmp/selenium/")
# options.add_argument('--headless')
options.add_argument('--start-maximized')
options.add_argument('--no-sandbox')
# options.add_argument('--auto-open-devtools-for-tabs')
# Chrome在/dev/shm中创建一个较大的临时文件,用于存储浏览器会话的数据。
# 这包括缓存、网页渲染过程中生成的中间结果等。
# 然而,使用Docker等容器技术时,/dev/shm通常被配置为非常小的大小,因此可能无法容纳Chrome所需的临时文件。
# docker运行必备,否则经常奔溃
options.add_argument('--disable-dev-shm-usage')
# 指定Firefox浏览器程序地址
# options.binary_location = '/usr/bin/chrome'
bro = Chrome(options=options)
# bro.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
# "source": """
# Object.defineProperty(navigator, 'webdriver', {
# get: () => undefined
# })
# """
# })
bro.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent": ua})
with open('/data/docker/selenium/stealth.min.js', 'r') as f:
js = f.read()
# 调用函数在页面加载前执行脚本
bro.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': js})
#第二个输入这个:隐藏式启动谷歌浏览器执行UI测试用例
# chrome_options = Options()
# chrome_options.add_argument('--headless')
# self.driver = webdriver.Chrome(options=chrome_options)
self.driver = bro