Scrapy与selenium,webdriver无法实例化

2024-05-23 13:55:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着用硒/幻影与刮胡,我是充满了错误。例如,使用以下代码段:

def parse(self, resposne):

    while True:
        try:
            driver = webdriver.PhantomJS()
            # do some stuff
            driver.quit()
            break
        except (WebDriverException, TimeoutException):
            try:
                driver.quit()
            except UnboundLocalError:
                print "Driver failed to instantiate"
            time.sleep(3)
            continue

很多时候,驱动程序似乎未能实例化(因此driver是未绑定的,因此出现异常),我得到了一个简介(以及我输入的打印消息)

Exception AttributeError: "'Service' object has no attribute 'process'" in <bound method Service.__del__ of <selenium.webdriver.phantomjs.service.Service object at 0x7fbb28dc17d0>> ignored

在google上搜索,似乎每个人都建议更新phantomjs,这是我从源代码构建的。有人知道是什么导致了这个问题和合适的诊断吗?


Tags: selfobjectparsedef代码段driver错误service
3条回答

这种行为的原因是PhantomJS驱动程序的^{} class是如何实现的。

定义了一个__del__方法来调用self.stop()方法:

def __del__(self):
    # subprocess.Popen doesn't send signal on __del__;
    # we have to try to stop the launched process.
    self.stop()

并且,self.stop()假设服务实例在尝试访问其属性时仍处于活动状态:

def stop(self):
    """
    Cleans up the process
    """
    if self._log:
        self._log.close()
        self._log = None
    #If its dead dont worry
    if self.process is None:
        return

    ...

同样的问题在本线程中得到了完美的描述:


您应该做的是静默地忽略退出驱动程序实例时发生的AttributeError

try:
    driver.quit()
except AttributeError:
    pass

这个问题是由这个revision引起的。这意味着降级到2.40.0也会有帮助。

我遇到了这个问题,因为phantomjs无法从脚本中获得(不在path中)。 您可以在控制台中运行phantomjs来检查它。

pypi上的Selenium版本2.44.0需要在Service.__init__selenium.webdriver.common.phantomjs.service中安装以下补丁

self.process = None

我想提交一个补丁,但这已经存在于google代码的most recent version中。

相关问题 更多 >