selenium.common.exceptions.WebDriverException:消息:打开chrome浏览器时无法连接到服务chromedriver.exe

Mil*_*van 3 python selenium webdriver selenium-chromedriver selenium-webdriver

我在本地 Chrome 67 Python 3.5.0 Selenium 3.12.0 有以下环境

我已经下载了 2.39 版的 chromedriver

我有 .py 文件如下

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(executable_path="hromedriver.exe")
driver.get('http://www.google.com')
time.sleep(5)
search_box = driver.find_element_by_name('q')
search_box.send_keys('Python')
search_box.submit()
time.sleep(5)
driver.quit()
Run Code Online (Sandbox Code Playgroud)

我收到以下错误。

C:\Python354\python.exe D:/formf.py
Traceback (most recent call last):
  File "D:/PCPNDT/form.py", line 4, in <module>
    driver = webdriver.Chrome(executable_path="chromedriver.exe")  # Optional argument, if not specified will search path.
  File "C:\Python354\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 68, in __init__
    self.service.start()
  File "C:\Python354\lib\site-packages\selenium\webdriver\common\service.py", line 104, in start
    raise WebDriverException("Can not connect to the Service %s" % self.path)
selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service chromedriver.exe
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用其他 webdriver,比如 geckodriver.exe 仍然是同样的错误。

请帮我解决这个错误。

谢谢!

Deb*_*anB 6

乍一看,您的代码试验似乎在参数executable_path中有一个小错误。而不是它应该是: hromedriver.exe

# Windows OS
driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe')
# Linux OS
driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
Run Code Online (Sandbox Code Playgroud)

这个错误信息...

selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service chromedriver.exe
Run Code Online (Sandbox Code Playgroud)

...暗示程序/脚本无法ChromeDriverService通过chromedriver.exe启动/生成。

错误的潜在原因可能是:

  • 由于缺少条目127.0.0.1 localhost/etc/hosts

解决方案

  • Windows 操作系统- 添加127.0.0.1 localhost/etc/hosts

  • Mac OSX - 确保以下条目:

    127.0.0.1   localhost
    255.255.255.255 broadcasthost
    ::1 localhost
    fe80::1%lo0 localhost   
    
    Run Code Online (Sandbox Code Playgroud)

参考

根据selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service geckodriver 中的讨论

  • Selenium 不需要127.0.0.1 localhost在主机文件中显式设置。
  • 但是,将localhost映射到IPv4 本地环回 (127.0.0.1)是强制性要求
  • 这种映射的机制不必总是通过主机文件。
  • Windows 操作系统系统上,它根本没有映射到主机文件中(解析 localhost 由 DNS 解析器完成)。

TL; 博士

如何将主机文件重置为默认值