【python爬虫】selenuim使用Chrome无头浏览器的配置方法

使用chrome无头浏览器
1
2
3
4
5
6
7
# 谷歌无头浏览器配置
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
if __name__ == "__main__":
bro = webdriver.Chrome(executable_path="../../chromedriver.exe", options=chrome_options)

selenium规避被检测识别

现在不少大网站有对selenium采取了监测机制。比如正常情况下我们用浏览器访问淘宝等网站的 window.navigator.webdriver的值为 undefined。而使用selenium访问则该值为true。那么如何解决这个问题呢? 只需要设置Chromedriver的启动参数即可解决问题。在启动Chromedriver之前,为Chrome开启实验性功能参数excludeSwitches,它的值为[‘enable-automation’],完整代码如下:

1
2
3
4
5
from selenium.webdriver import Chrome
from selenium.webdriver import ChromeOptions
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = Chrome(options=option)
两个板块一次性配置:
1
2
3
4
5
6
7
8
9
10
# 谷歌无头浏览器配置
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
# 规避被检测配置
chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])

if __name__ == "__main__":
bro = webdriver.Chrome(executable_path="../../chromedriver.exe", options=chrome_options)