Selenium 启动浏览器但显示错误消息:无法连接到服务

Selenium starts the browser but shows an error as Message: Can not connect to the Service

代码启动浏览器,停在这一步(第 5 行),一段时间后抛出错误:

selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service C:\Program Files\Mozilla Firefox\firefox.exe

from selenium import webdriver
from selenium.webdriver.firefox.service import Service

s = Service(r'C:\Program Files\Mozilla Firefox\firefox.exe')
driver = webdriver.Firefox(service=s)
driver.get('http://www.google.com')
myPageTitle = driver.title
print(myPageTitle)
driver.quit()

火狐 - 95.0.2 硒 - 4.1.0

我试过 chrome,同样的问题

有人知道问题是什么以及如何解决吗?

作为 Service() 而非 executable, you need to pass the absolute location of the GeckoDriver executable which can be downloaded from mozilla/geckodriver 页面的参数。

因此您的有效代码块将是:

from selenium import webdriver
from selenium.webdriver.firefox.service import Service

s = Service(r'C:\path\to\geckodriver.exe')
driver = webdriver.Firefox(service=s)
driver.get('http://www.google.com')
myPageTitle = driver.title
print(myPageTitle)
driver.quit()