我创建了一个类作为selenium driver
的基本设置。我给它添加了一些方法。我想从上下文管理器访问该类的方法我试图在context manager
中创建该类的对象并访问该方法,但失败了。我该怎么做
我甚至不知道这段代码有什么错。请帮帮我
class SeleniumDriver:
'''basic setup for chromedriver(selenium)'''
def __init__(self,
driversource='C:\\Users\Ewis\Downloads\chromedriver.exe',
url = ('https://realpython.com/')
):
self.driversource = driversource
self.url = url # this tuple
def __enter__(self):
self.driver = webdriver.Chrome(executable_path=self.driversource)
for urls in self.url:
self.driver.get(urls)
return self.driver, Keys
def __exit__(self, exc_type, exc_val, exc_trace):
self.driver.quit()
# and this code(another project)
from seleniumdriver import SeleniumDriver
with SeleniumDriver() as packed:
seldriver1 = SeleniumDriver()
driver = packed[0]
urls = ('https://realpython.com/','https://stackoverflow.com/')
resp = seldriver1.geturl(urls)
for url in resp:
title, url = resp.titleurl()
print(title, '\n', url,'\n')
错误:
Traceback (most recent call last): File "C:\python\progs\web\selenium\navigation_commands\navigation_commands.py", line 9, in for url in resp: File "c:\python\progs\my_modules\seleniumdriver\seleniumdriver.py", line 22, in geturl yield (self.driver).get(url) AttributeError: 'SeleniumDriver' object has no attribute 'driver'
我不确定这是否足以解决所有问题,但:
你必须使用
packed[0]
,它是用with
创建的,它执行__enter__
,它创建self.driver
但是您使用
seldriver1
,它是使用不执行__enter__
的seldriver1 = SeleniumDriver()
创建的,因此它不会创建self.driver
(seldriver1.driver
),您会得到错误:你的代码对我来说似乎很奇怪,可能需要更多的修改才能正常工作
编辑:这段代码适合我
因为我在Linux上使用Firefox,而且我不必设置
driversource
,所以我添加了None
以在没有driversource
的情况下运行我从
__enter__
中删除了get(url)
,因为它是无用的。您无法在__enter__
中获取两个页面并稍后在for
循环中使用它们,因为打开第二个页面时Selenium
不会保留第一个页面的信息相关问题 更多 >
编程相关推荐