WebDriverException:服务 U:/Scraping/chromedriver.exe 意外退出。状态代码为:1 使用 Chrome 和 Python 时

Jac*_*ler 5 python selenium google-chrome selenium-chromedriver selenium-webdriver

我一直在尝试让 webdriver 在工作中与 Chrome 中的 Python 一起工作,但我终其一生都无法弄清楚出了什么问题,尽管一天中的大部分时间都在进行故障排除。

我已将 chromedriver 解压缩到我正在使用的文件夹中。我尝试将executable_path参数与 chromedriver 一起使用。我尝试更新 chromedriver 中的选项以指向 Chrome.exe 文件。

代码如下。很简单。'url' 有一个来自代码前面的地址,我没有在这里包括 - 脚本甚至没有让它走那么远。

from selenium import webdriver

driver = webdriver.Chrome(executable_path = 'U:/Scraping/chromedriver.exe')
driver.get(url)
Run Code Online (Sandbox Code Playgroud)

和错误:

    Traceback (most recent call last):

  File "<ipython-input-67-db2ce2aa7cdf>", line 1, in <module>
    runfile('U:/Scraping/Project.py', wdir='U:/Scraping')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "U:/Scraping/Project.py", line 14, in <module>
    driver = webdriver.Chrome(executable_path = 'U:/Scraping/chromedriver.exe')

  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 68, in __init__
    self.service.start()

  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\common\service.py", line 98, in start
    self.assert_process_still_running()

  File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\common\service.py", line 111, in assert_process_still_running
    % (self.path, return_code)

WebDriverException: Service U:/Scraping/chromedriver.exe unexpectedly exited. Status code was: 1
Run Code Online (Sandbox Code Playgroud)

Deb*_*anB 1

通过参数executable_path传递ChromeDriver二进制文件的绝对路径时,您需要提及单引号(即)内的路径,并用单个正斜杠(即)与原始开关(即)分隔,如下所示:''\r

from selenium import webdriver

driver = webdriver.Chrome(executable_path=r'U:\Scraping\chromedriver.exe')
driver.get(url)
Run Code Online (Sandbox Code Playgroud)

额外考虑因素

  • 确保您已从与底层操作系统相关的下载位置下载了准确格式的ChromeDriver二进制文件:

    • chromedriver_win32.zip:适用于Windows 操作系统
  • 确保非管理员用户的ChromeDriver二进制文件具有可执行权限 。

  • 非管理员用户身份执行测试
  • 错误的另一个潜在原因可能是由于缺少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 解析器完成)。

长话短说

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