如何避免获得''NoneType'对象在selenium quit()上没有属性'path'`?

时间:2016-12-06 15:26:42

标签: python selenium exception selenium-webdriver webdriver

运行 Selenium Webdriver Python脚本时,在执行'NoneType' object has no attribute 'path'后获得self.driver.quit().self.driver.quit()中封闭try/except不会帮助,即:

$ cat demo_NoneType_attribute_error.py
# -*- coding: utf-8 -*-
from selenium import webdriver
import unittest

class TestPass(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()

    def test_pass(self):
        pass

    def tearDown(self):
        print("doing: self.driver.quit()")
        try:
            self.driver.quit()
        except AttributeError:
            pass

if __name__ == "__main__":
    unittest.main()

$ python demo_NoneType_attribute_error.py
doing: self.driver.quit()
'NoneType' object has no attribute 'path'
.
----------------------------------------------------------------------
Ran 1 test in 19.807s

OK

$

有没有人知道如何避免'NoneType' object has no attribute 'path'消息?

注意:
由于此问题已在11月初报告过(请参阅下面的网址),它现在应该有一个补丁 - 但将selenium升级到pip的最新版本并没有消除它。

环境:硒3.0.2; Python 2.7; Windows 7上的Cygwin 32位。

1 个答案:

答案 0 :(得分:5)

这似乎是selenium 3.0

中的错误

更新quit() webdriver.py中的firefox方法定义,如下所示(相对路径:..\Python27\Lib\site-packages\selenium\webdriver\firefox\webdriver.py):

更改quit()方法中的以下行:

shutil.rmtree(self.profile.path) #which gives Nonetype has no attribute path
if self.profile.tempfolder is not None:
    shutil.rmtree(self.profile.tempfolder)

if self.profile is not None:
    shutil.rmtree(self.profile.path) # if self.profile is not None, then only rmtree method is called for path.
    if self.profile.tempfolder is not None:
        shutil.rmtree(self.profile.tempfolder) # if tempfolder is not None, then only rmtree is called for tempfolder.

注意:在使用self.profile的地方,执行相同的操作。即,将代码移动到如上所述的条件。

Selenium 3.0中,profilebinary移至firefox_options,而不是firefox_profilefirefox_binary分别在Selenium 2.0 }}

您可以在webdriver.py firefox方法的__init__ __init__中验证这一点。

if firefox_options is None: firefox_options = Options() print dir(firefox_options) # you can refer binary and profile as part of firefox_options object. 方法中的相关代码:

firefox_options.profile

注意:观察到None仍在提供selenium 3.0,这可能是greet(param1 on: param2)

中要解决的问题