首页 > 解决方案 > selenium.common.exceptions.WebDriverException:消息:打开 chrome 浏览器时无法连接到服务 chromedriver.exe

问题描述

我在本地 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()

我收到以下错误。

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

我也尝试使用其他 webdriver 像 geckodriver.exe 仍然同样的错误。

请帮我解决这个错误。

谢谢!

标签: pythonseleniumselenium-webdriverwebdriverselenium-chromedriver

解决方案


乍一看您的代码试用版,参数 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')

此错误消息...

selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service chromedriver.exe

...意味着程序/脚本无法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   
    

参考

根据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 操作系统上,它根本没有映射到 hosts 文件中(解析 localhost 是由 DNS 解析器完成的)。

TL;博士

如何将 Hosts 文件重置为默认值


推荐阅读