【问题标题】:Subclassed object results in NoneType子类化对象导致 NoneType
【发布时间】:2016-07-17 02:12:39
【问题描述】:

我正在尝试对 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'

【问题讨论】:

    标签: python python-3.x selenium subclass


    【解决方案1】:

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

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

    要了解有关此功能的原因和方式的更多信息,请参阅:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-11
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多