我开设了一门课,作为硒驱动器的基本设置。并且我添加了方法。我想从上下文管理器访问类的方法,我试图在上下文管理器中创建类的对象并访问该方法,但失败了。我该怎么办?
我什至不知道这段代码有什么问题。请帮助我。
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 <module>
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'
答案 0 :(得分:0)
我不确定是否足以解决所有问题,但:
您必须使用packed[0]
,它是使用with
创建的,它执行__enter__
会创建self.driver
resp = packed[0].geturl(urls)
但是您使用的seldriver1
是使用seldriver1 = SeleniumDriver()
创建的,它不会执行__enter__
,因此不会创建self.driver
(seldriver1.driver
),并且您得到错误:
'SeleniumDriver' object has no attribute 'driver'
from seleniumdriver import SeleniumDriver
with SeleniumDriver() as packed:
urls = ('https://realpython.com/','https://stackoverflow.com/')
resp = packed[0].geturl(urls)
for url in resp:
title, url = resp.titleurl()
print(title, '\n', url,'\n')
您的代码对我来说似乎很奇怪,它可能需要更多更改才能正常工作。
编辑:该代码对我有用。
因为我在Linux上使用了Firefox,而不必设置driversource
,所以我添加了None
以在没有driversource
的情况下运行
我从get(url)
中删除了__enter__
,因为它没有用。您无法在__enter__
中获得两页,而以后在for
循环中使用它们,因为Selenium
在打开第二页时不会保留有关第一页的信息。
from selenium import webdriver
class SeleniumDriver:
'''basic setup for chromedriver(selenium)'''
def __init__(self, driversource='C:\\Users\Ewis\Downloads\chromedriver.exe'):
self.driversource = driversource
def __enter__(self):
if self.driversource:
#self.driver = webdriver.Chrome(executable_path=self.driversource)
self.driver = webdriver.Firefox(executable_path=self.driversource)
else:
#self.driver = webdriver.Chrome()
self.driver = webdriver.Firefox()
return self.driver
def __exit__(self, exc_type, exc_val, exc_trace):
self.driver.quit()
with SeleniumDriver(None) as driver:
urls = ('https://realpython.com/', 'https://stackoverflow.com/')
for url in urls:
driver.get(url)
title = driver.title
print(title, '\n', url,'\n')