開發環境
操作系統 | Mac OS 10.13.6 |
Python | 3.7 |
Chrome | 72.0 |
chromedriver | 2.45 |
使用selenium庫下webdriver模塊打開谷歌瀏覽器時報錯,代碼如下:
from selenium import webdriver
# 創建瀏覽器對象
driver = webdriver.Chrome() # Chrome是谷歌瀏覽器(驅動:chromedriver),也可以更改其他瀏覽器注:更換其他瀏覽器時,需要安裝瀏覽器相對應的驅動
driver.get('https://www.baidu.com') # 打開百度網頁
driver.close() # 關閉瀏覽器
錯誤信息(1):
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
chrome瀏覽器版本相對應的chromedriver版本,參考鏈接:
https://chromedriver.storage.googleapis.com/2.46/notes.txt
下載chromedriver驅動連接:
https://chromedriver.storage.googleapis.com/index.html
chromedriver驅動複製"/usr/local/bin"目錄下
,chromedriver驅動文件路徑需要添加到系統配置文件中
vim ~/.bash_profile
點 i 鍵進入編輯模式,進行編輯(必須是英文下的大寫字母或者小寫字母)
添加文件路徑:export PATH=$PATH:/usr/local/bin/chromedriver
編輯完成後,點esc 退出
輸入" :wq! ",這四個字符後,回車即可保存
運行上述代碼打開Google瀏覽器
Firefox配置步驟與Google瀏覽器相同,Geckodriver驅動下載地址:
https://github.com/mozilla/geckodriver/releases
錯誤信息(2):
selenium.common.exceptions.WebDriverException: Message: Host header or origin header is specified and is not localhost——指定了主機報頭或源報頭,而不是本地主機。
解決方法:
下載瀏覽器所兼容的chromedriver驅動
錯誤信息(3):
selenium.common.exceptions.WebDriverException:Message: Service chromedriver unexpectedly exited. Status code was: 126:chrome服務意外退出,狀態碼是:126
解決方案:
最新版本谷歌瀏覽器沒有所兼容的chromedriver驅動,需要更換googlechrome版本,googlechrome版本必須兼容chromedriver驅動
查看版本信息 ⋮——>幫助——>關於Google Chrome