zl程序教程

您现在的位置是:首页 >  其他

当前栏目

FAQ Selenium中提示can not connect to the service chromedriver 的解决方法

2023-04-18 14:53:41 时间

can not connect to the service chromedriver问题的处理

背景

  • 一个同学反馈运行如下代码

     from selenium import webdriver   
     from  time import sleep
     driver = webdriver.Chrome()    
     driver.get("https://cn.bing.com")
     driver.find_element("id","sb_form_q").send_keys("松勤软件测试 ")    
     sleep(3)                                  
     driver.quit()  
  • 报错了

     

  • 一看这个错误没见到过,驱动应该是有的,版本也应该对的,无法连接到chromedriver

  • 考虑到chromedriver本身就是一个web server

     C:Userssongqin008>chromedriver
     Starting ChromeDriver 103.0.5060.134 (8ec6fce403b3feb0869b0732eda8bd95011d333c-refs/branch-heads/5060@{#1262}) on port 9515
     Only local connections are allowed.
     Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
     ChromeDriver was started successfully.
     
  • 其实你是可以在浏览器中访问http://127.0.0.1:9515/的,当然这个get并不会返回太多有用的信息,只能说可以看到。

 

解决

  • 一开始我只想到这里,但不知道如何解决

  • 搜索引擎一查,说是hosts文件可能会影响

  • 查了下这位同学的hosts

  • 少了下面一行

     127.0.0.1 localhost
  • 加上后解决 

思考

  • 猜猜:代码自动调起chromedriver,并作为webserver访问其api,这个地址可能是127.0.0.1?但没有找到所以报错。

  • 搜索代码发现,报错信息在seleniumwebdrivercommonservice.py,105行

             while True:
                 self.assert_process_still_running()
                 if self.is_connectable():
                     break
     
                 count += 1
                 sleep(0.5)
                 if count == 60:
                     raise WebDriverException("Can not connect to the Service %s" % self.path)
  • 30秒超时时间会提示这个,跟实际代码运行效果类似。

  • 那代码self.is_connectable()就应该是不为True的

         def is_connectable(self):
             return utils.is_connectable(self.port)
  • 再看is的定义

     def is_connectable(port: int, host: Optional[str] = "localhost") -> bool:
      pass #略
  • 答案呼之欲出,上面的代码默认值就是localhost

  • 你现在没有这个,自然就不行咯