为了帮助调试此问题,您可以使用 selenium webdriver 的 service_log_path 和 service_args 参数来查看 chromedriver 的输出:
service_log_path = "{}/chromedriver.log".format(outputdir)
service_args = ['--verbose']
driver = webdriver.Chrome('/path/to/chromedriver',
service_args=service_args,
service_log_path=service_log_path)
我收到了同样的异常消息,并找到了两种解决方法;我不确定 OP 的问题是否相同,但如果不是,chromedriver 日志有望有所帮助。查看我的日志,我发现 chromedriver(我在尝试解决此问题时尝试从 2.9 降到 2.6)以一种非常意想不到的方式决定运行哪个浏览器。在我的 chromedriver 所在的目录中,我有这些文件:
$ ls -l /path/to/
-rwx------ 1 pjh grad_cs 5503600 Feb 3 00:07 chromedriver-2.9
drwxr-xr-x 3 pjh grad_cs 4096 Mar 28 15:51 chromium
当我使用与 OP 相同的 python 代码调用 chromedriver 时:
driver = webdriver.Chrome('/path/to/chromedriver-2.9')
这会导致异常消息。在 chromedriver.log 中,我发现了这条消息:
[1.043][INFO]: Launching chrome: /path/to/chromium ...
难以置信! chromedriver 正在尝试使用/path/to/chromium(不是可执行文件,而是包含源代码的目录)作为浏览器来执行!显然 chromedriver 在搜索我的PATH 之前尝试搜索当前目录以查找要运行的浏览器。因此,解决此问题的一个简单方法是检查chromedriver 所在的目录中的文件/目录,例如chrome 和chromium,并将它们移动到与chromedriver 不同的目录。
更好的解决方案是使用 chrome_options 参数明确告诉 selenium / chromedriver 执行哪个浏览器:
options = webdriver.ChromeOptions()
options.binary_location = '/opt/google/chrome/google-chrome'
service_log_path = "{}/chromedriver.log".format(outputdir)
service_args = ['--verbose']
driver = webdriver.Chrome('/path/to/chromedriver',
chrome_options=options,
service_args=service_args,
service_log_path=service_log_path)
chromedriver.log 现在显示:
[0.999][INFO]: Launching chrome: /opt/google/chrome/google-chrome ...
正如预期的那样。