[英]Python Error: AttributeError: __enter__ using Selenium
我正在尝试运行我的 selenium 测试,但出现错误。
首先,我正在创建 booking.py 文件,其中包含 Booking class:
from asyncio import selector_events
from lib2to3.pgen2 import driver
import booking.constants as const
import os
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
class Booking:
def __init__(self, teardown = False):
s = Service(ChromeDriverManager().install())
self.driver = webdriver.Chrome(service=s)
self.driver.get(const.BASE_URL)
self.driver.teardown = teardown
self.driver.implicitly_wait(15)
def __exit__(self, exc_type, exc_val, exc_tb):
if self.driver.teardown:
self.driver.quit()
def cookies(self):
self.driver.find_element(By.ID, 'onetrust-accept-btn-handler').click()
def select_place_to_go(self):
self.driver.find_element(By.ID, "ss").click()
然后,我有 run.py 文件:
from booking.booking import Booking
with Booking() as bot:
bot.cookies()
bot.select_place_to_go()
运行 run.py 文件后,出现错误:
AttributeError: __enter__
但是,使用此代码完全可以正常工作:
bot = Booking()
bot.cookies()
bot.select_place_to_go()
问题出在哪里? 如果您对代码改进有任何想法,请告诉我。 任何帮助表示赞赏,谢谢
我猜你错过了__enter__
上的 __enter__ function。 在Python中使用with块时,调用with语句中object的__enter__
方法,运行with内部的块,并调用__exit__
方法。 如果您的__enter__
没有定义 __enter__,您将收到此错误。 所以你必须在Booking
class 中定义__enter__
方法并在其中返回 self
def select_place_to_go(self, place_to_go):
search_field = self.find_element(By.ID, 'ss').click()
search_field.clear()
search_field.send_keys(place_to_go)
这是我使用的代码,我运行它没有任何问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.