gpt4 book ai didi

python - 子类化对象导致 NoneType

转载 作者:行者123 更新时间:2023-12-01 03:49:55 29 4
gpt4 key购买 nike

我尝试对 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__()魔术方法应该返回self,以便driver变量指向WebDriver<的实例类:

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

要获取有关其工作原理和原理的更多信息,请参阅:

关于python - 子类化对象导致 NoneType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38417289/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com