所謂瀏覽器的無(wú)頭模式headless
妒茬,就是瀏覽器在運(yùn)行時(shí)處于后臺(tái)操作的模式艺挪,不會(huì)看到瀏覽器打開胰伍,也就不會(huì)干擾你手頭的工作弓千。對(duì)于自動(dòng)化測(cè)試和網(wǎng)絡(luò)爬蟲都有很大的價(jià)值萍诱。
早期我們使用 phantomJS 瀏覽器來(lái)實(shí)現(xiàn)這種模式宫静,隨著 Chrome 和 Firefox 都加入了無(wú)頭模式涨椒, Selenium 逐漸停止對(duì) phantomJS 的支持斑司。
Chrome 的 headless
Chrome 的無(wú)頭模式,通過(guò)在打開瀏覽器前加入 --headless
參數(shù)配置即可實(shí)現(xiàn)姻政。
from selenium import webdriver
from selenium.webdriver.chrome.options import Options # => 引入Chrome的配置
import time
# 配置
ch_options = Options()
ch_options.add_argument("--headless") # => 為Chrome配置無(wú)頭模式
# 在啟動(dòng)瀏覽器時(shí)加入配置
driver = webdriver.Chrome(chrome_options=ch_options) # => 注意這里的參數(shù)
driver.get('http://baidu.com')
driver.find_element_by_id('kw').send_keys('測(cè)試')
driver.find_element_by_id('su').click()
time.sleep(2)
# 只有截圖才能看到效果咯
driver.save_screenshot('./ch.png')
driver.quit()
Firefox 的 headless
Firefox 瀏覽器的無(wú)頭模式配置與 Chrome 差不多呆抑,只是寫法有差異。
from selenium.webdriver.firefox.options import Options # => 引入Firefox配置
from selenium import webdriver
import time
# 配置瀏覽器
ff_options = Options()
ff_options.headless = True # => 設(shè)置無(wú)頭模式為 True
driver = webdriver.Firefox(firefox_options=ff_options) # => 注意這里的參數(shù)
driver.get('http://baidu.com')
driver.find_element_by_id('kw').send_keys('測(cè)試')
driver.find_element_by_id('su').click()
time.sleep(2)
# 截圖看效果
driver.save_screenshot('./ff.png')
driver.quit()
感受一下吧汁展!