python - PhantomJS - 连接到 GhostDriver 错误

标签 python selenium python-3.x selenium-webdriver phantomjs

我正在使用 PhantomJS 和 Selenium 抓取网站。我的问题是,在检查了大约 50 个 URL 后,我出现了一个错误:

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

我不知道如何修复它,我尝试了两个 PhantomJS 版本(1.9 和 1.98),但它仍然无法正常工作。你有什么想法吗?

这是我正在执行的代码:

def get_car_price(self, car_url): 
    browser = webdriver.PhantomJS('C:\phantomjs.exe') 
    browser.get(car_url) 
    content = browser.page_source 
    browser.quit() 

    website = lh.fromstring(content) 
    for price in website.xpath('//*[@id="js_item_' + str(self.car_id) + '"]/div[1]/div[2]/div[2]/strong[2]'): 
        return price.text

最佳答案

不要打开/退出 PhantomJS 浏览器,而是保持打开状态并重新使用它。在脚本启动时全局创建它,并在脚本即将完成时退出。

例子:

class Service(object):
    def __init__(self):
        self.browser = webdriver.PhantomJS('C:\phantomjs.exe') 

    def get_car_price(self, car_url): 
        self.browser.get(car_url) 
        content = self.browser.page_source 

        website = lh.fromstring(content) 
        for price in website.xpath('//*[@id="js_item_' + str(self.car_id) + '"]/div[1]/div[2]/div[2]/strong[2]'): 
            return price.text

    def shutdown(self):
        self.browser.quit() 

service = Service()
try:
    for url in urls:
        print(service.get_car_price(url))
finally:
    service.shutdown()

关于python - PhantomJS - 连接到 GhostDriver 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27691364/

相关文章:

python - 使用二元分类器模型将数据分为 3 类

java - 使用 Selenium 循环链接

python - 发送带有正文的 GET 请求

python - 从简单的 pandas 数据帧创建矩阵

python - 修补 Python 模块时 Django 中的 Gevent 异常

python - 在 python View 中检测移动浏览器(不仅仅是 iPhone)

python - 将文件写入 Google 应用引擎 Blobstore,因为这些方法将被弃用

selenium - 如何在Selenium远程WebDriver中禁用Flash

java - 如何在selenium中使用其属性及其文本来查找html标签?

python - 低特征环境的鲁棒定位