Selenium无法连接GhostDriver(但只有有时)

9 投票
1 回答
6382 浏览
提问于 2025-04-18 12:08

我在Python中用Selenium和PhantomJS设置了一个简单的网页抓取脚本。总共有大约200个网址需要抓取。这个脚本一开始运行得很好,但在抓取大约20到30个网址后(具体数量似乎是随机的,跟某个特定网址没有关系),我在Python中遇到了以下错误:

selenium.common.exceptions.WebDriverException: Message: 'Can not connect to GhostDriver'

还有我的ghostdriver.log日志:

PhantomJS is launching GhostDriver...
[ERROR - 2014-07-04T17:27:37.519Z] GhostDriver - main.fail - {"message":"Could not start Ghost Driver","line":82,"sourceId":140692115795456,"sourceURL":":/ghostdriver/main.js","stack":"Error: Could not start Ghost Driver\n    at :/ghostdriver/main.js:82","stackArray":[{"sourceURL":":/ghostdriver/main.js","line":82}]}

我查了一下,发现大多数人在StackOverflow上提问时,都是因为他们连一个网址都无法运行。只有一个问题是我找到的,错误发生在脚本中间,链接是这个,答案是升级phantomjs到最新版本,我已经做了。另一个答案只是建议再试一次那个网址,但我觉得这不是个好办法,因为那个网址可能会再次失败。

我在Linux Mint 17上运行的是phantomjs 1.9.7版本和selenium 2.42.1版本,使用的是Python 2.7.6。

for url in ['example.com/1/', 'example.com/2/', 'example.com/3/', .. , ..]:
    user_agent = 'Chrome'
    dcap = dict(DesiredCapabilities.PHANTOMJS)
    dcap['phantomjs.page.settings.userAgent'] = user_agent
    driver = webdriver.PhantomJS(executable_path='/usr/bin/phantomjs', desired_capabilities=dcap)
    driver.get(url)

1 个回答

8

我也遇到过同样的问题,解决这个问题的方法是我从源代码安装了phantomjs

For Linux (Debian):
sudo apt-get update
sudo apt-get install build-essential chrpath git-core libssl-dev libfontconfig1-dev libxft-dev
git clone git://github.com/ariya/phantomjs.git
cd phantomjs
git checkout 1.9
./build.sh

For Mac os:
git clone git://github.com/ariya/phantomjs.git
cd phantomjs
git checkout 1.9
./build.sh

如果你使用其他系统,可以查看以下链接:http://phantomjs.org/build.html

Optional :
cd bin
chmod +x phantomjs
cp phantomjs /usr/bin/

我之所以找到解决办法,是因为我查看了我的ghostdriver.log文件,里面有提示。

[ERROR - 2014-09-04T19:33:30.842Z] GhostDriver - main.fail - {"message":"Could not start Ghost Driver","line":82,"sourceId":140145669488128,"sourceURL":":/ghostdriver/main.js","stack":"Error: Could not start Ghost Driver\n    at :/ghostdriver/main.js:82","stackArray":[{"sourceURL":":/ghostdriver/main.js","line":82}]}

我觉得一定是缺少了一些文件,这些文件可能在某些特殊情况下会用到。所以我决定从源代码构建,结果现在一切正常。

撰写回答