在python腳本中,使用selenium啟動瀏覽器報錯,原因是未安裝瀏覽器驅動,報錯內容如下:
# -*- coding:utf-8 -*-
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.baidu.com")
報錯提示如下所示:
Traceback (most recent call last):
File "D:\Program Files\Python36\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start
stdin=PIPE)
File "D:\Program Files\Python36\lib\subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "D:\Program Files\Python36\lib\subprocess.py", line 997, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] 系統找不到指定的文件。
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/Program Files/Python36/baidu.py", line 4, in <module>
driver = webdriver.Firefox()
File "D:\Program Files\Python36\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 164, in __init__
self.service.start()
File "D:\Program Files\Python36\lib\site-packages\selenium\webdriver\common\service.py", line 83, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.
解決方案:安裝Chrome瀏覽器驅動
1.下載 chromedriver_win32.zip,根據瀏覽器版本下載對應的壓縮包;
下載地址:https://sites.google.com/a/chromium.org/chromedriver/downloads
2.解壓后將chromedriver.exe文件放到系統環境變量Path路徑下,例如:已將D:\Program Files\Python36\ 添加到系統環境變量Path路徑下,將chromedriver.exe文件放到D:\Program Files\Python36\ 目錄下即可;
3.將Chrome替換掉原腳本中的Firefox,保存文件並運行。
# -*- coding:utf-8 -*-
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
driver.find_element_by_id("kw").send_keys("Selenium2")
driver.find_element_by_id("su").click
driver.quit()
原文:https://blog.csdn.net/weixin_44612439/article/details/87983282
