如果使用PhantomJS,权限错误

时间:2016-03-22 11:19:09

标签: python selenium selenium-webdriver phantomjs

我有一个Selenium-Python脚本,可以与FirefoxChrome配合使用,但如果使用PhantomJS,有时会引发以下异常:

Exception ignored in: <bound method Service.__del__ of <selenium.webdriver.phant
omjs.service.Service object at 0x000000000439FE80>>
Traceback (most recent call last):
File "C:\Python34\Lib\site-packages\selenium\webdriver\common\service.py", line 151, in __del__
self.stop()
File "C:\Python34\Lib\site-packages\selenium\webdriver\common\service.py", line 127, in stop
self.send_remote_shutdown_command()
File "C:\Python34\Lib\site-packages\selenium\webdriver\phantomjs\service.py", line 68, in send_remote_shutdown_command
os.remove(self._cookie_temp_file)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\OB865~1.LUC\\AppData\\Local\\Temp\\tmpe6zrcjem'

脚本的要点是遍历文件列表:为每个文件启动浏览器会话,发送文件进行分析,获取并保存结果,关闭浏览器。会话重新打开时(driver.close()driver = webdriverPhantomJS()之间)在大约50%的情况下进行下一次迭代时出现问题...

关于什么可能导致这个问题以及如何解决这个问题的任何假设?

P.S。如果需要任何其他信息,请告诉我

2 个答案:

答案 0 :(得分:5)

我发现问题是系统试图删除在浏览器会话期间创建的临时文件,但并不总是成功。 通过改变selenium.webdriver.phantomjs.service.py中的功能来解决,如下所示:

def send_remote_shutdown_command(self):
    if self._cookie_temp_file:
            os.remove(self._cookie_temp_file)
添加try/except构建后

def send_remote_shutdown_command(self):
    try:
        if self._cookie_temp_file:
            os.remove(self._cookie_temp_file)
    except PermissionError:
        pass

如果webdriver无法执行此操作,则可以避免临时文件删除。文件实际上是空的(0kb),因此即使大量此类临时文件也不会损害系统

答案 1 :(得分:1)