要模擬瀏覽器訪問網頁,網上較普遍的是用selenium+chromedriver+chrome瀏覽器。
一,安裝selenium第三方庫
在cmd命令行串口輸入pip install selenium
二,安裝webdriver
網上主要有三類瀏覽器,chrome和firefox和ie,我習慣用360安全瀏覽器,它采用的是chrome內核。
下載chromedriver,需要與瀏覽器的版本相對應。我瀏覽器的版本是63,對應的chromedriver版本是2.36,到下面的地址下載對應的版本。
http://chromedriver.storage.googleapis.com/index.html
將chromedriver.exe所在目錄加入到windows的環境變量path中
三,輸入下面代碼
from selenium import webdriver browser = webdriver.Chrome() browser.get('http://www.baidu.com/')
倒霉,運行出錯,主要提示如下:
cannot find Chrome binary
原因分析:大概意思就是chrome瀏覽器未找到,經過網上大量找資料,回頭終於發現,只要將啟動瀏覽器的啟動exe文件改個名就行,即將360se.exe改為chrome.exe即可。
這樣,程序就可以驅動瀏覽器了。
也可以這樣:
from selenium import webdriver option=webdriver.ChromeOptions() option.binary_location=r'C:\360se\360se6\Application\360se.exe' drive=webdriver.Chrome(r'C:\360se\360se6\Application\chromedriver.exe',options=option) drive.get('http://www.lcez.com.cn')
四,注:上面是普通模式啟動瀏覽器,還有另外一種 靜默模式,即不顯示瀏覽器界面。
option.add_argument('--headless')
在這里出現了錯誤
Message: session not created exception: Chrome version must be >= 62.0.3202.0
原因未知,但換成chrome瀏覽器,則正常, 如下:
option=webdriver.ChromeOptions() option.add_argument('--headless') drive=webdriver.Chrome(options=option) drive.get('http://lcez.com.cn') print(drive.title) drive.quit()