子类对象导致 NoneType
Subclassed object results in NoneType
我正在尝试子类化 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'
你的 __enter__()
魔术方法应该 return self
使 driver
变量指向 WebDriver
class 的实例:
def __enter__(self):
self.get(self.url)
self.implicitly_wait(15)
return self
要了解有关其工作原理和原理的更多信息,请参阅:
- Understanding Python's "with" statement
- Explaining Python's '__enter__' and '__exit__'
我正在尝试子类化 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'
你的 __enter__()
魔术方法应该 return self
使 driver
变量指向 WebDriver
class 的实例:
def __enter__(self):
self.get(self.url)
self.implicitly_wait(15)
return self
要了解有关其工作原理和原理的更多信息,请参阅:
- Understanding Python's "with" statement
- Explaining Python's '__enter__' and '__exit__'