-selenium 是基于浏览器自动化模块
-phantomJs是一款无可视化界面的浏览器 (已经弃用)
selenium 基本操作
官方参考文档:http://selenium-python.readthedocs.io/index.html
谷歌驱动下载:http://chromedriver.storage.googleapis.com/index.html
火狐驱动下载:https://github.com/mozilla/geckodriver/releases
无头浏览器谷歌配置
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)
无头浏览器火狐配置
from selenium.webdriver.firefox.options import Options #导入无头浏览器模块
#创建一个对象,用来控制chrome以无界面模式打开
firefox_options = Options()
firefox_options.add_argument('--headless')
firefox_options.add_argument('--disable-gpu')
driver = webdriver.Firefox(firefox_options=firefox_options)
规避网站检测
现在不少大网站有对selenium采取了监测机制。比如正常情况下我们用浏览器访问淘宝等网站的在控制台打印window.navigator.webdriver
的值为undefined。而使用selenium访问则该值为true。
解决:
只需要设置Chromedriver
的启动参数即可解决问题。在启动Chromedriver
之前,为Chrome开启实验性功能参数excludeSwitches
,它的值为['enable-automation']
,完整代码如下:
from selenium.webdriver import ChromeOptions # 需要导入的类
# 创建 option 对象
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
# 创建浏览器对象
driver = webdriver.Chrome(options=option)
driver.get('https://www.taobao.com/')
chrome 79以后版本
driver = webdriver.Chrome(r'C:\Users\Lenovo\Documents\study\初识爬虫\chromedriver.exe')
url = 'https://www.taobao.com/'
driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
"source": """
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
})
"""
})