Subclassed对象导致NoneType

时间:2016-07-17 02:12:39

标签: python python-3.x selenium subclass

我正在尝试将Chrome WebDriver子类化为包含一些初始化和清理代码,但是Python抱怨所创建的对象设置为None

import glob
import selenium
import subprocess
from selenium.webdriver.common.by import By


class WebDriver(selenium.webdriver.Chrome):
    def __init__(self, url, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.url = url

    def __enter__(self):
        self.get(self.url)
        self.implicitly_wait(15)

    def __exit__(self, type, value, traceback):
        self.quit()
        for path in glob.glob('/tmp/.org.chromium.Chromium.*'):
            subprocess.run(['rm', '-rf', path], check=True)


with WebDriver('https://google.com') as driver:
    driver.find_element(By.ID, 'lst-ib').send_keys('Search')

使用Python 3运行代码:

$ python3 test.py
Traceback (most recent call last):
  File "test.py", line 43, in <module>
    driver.find_element(By.ID, 'lst-ib').send_keys('Search')
AttributeError: 'NoneType' object has no attribute 'find_element'

1 个答案:

答案 0 :(得分:2)

您的__enter__()魔术方法应返回self,以使driver变量指向WebDriver类的实例:

def __enter__(self):
    self.get(self.url)
    self.implicitly_wait(15)
    return self

要了解有关其原因和方法的更多信息,请参阅: