简体   繁体   中英

Python Error: AttributeError: __enter__ using Selenium

I am trying to run my selenium test, but I get an error.

First, I am creating booking.py file, which contains 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()

Then, I have run.py file:

from booking.booking import Booking

with Booking() as bot:
    bot.cookies()
    bot.select_place_to_go()

After running run.py file, I get an error:

AttributeError: __enter__

However, it works completely fine using this code:

bot = Booking()
bot.cookies()
bot.select_place_to_go()

Where is the problem? f you have any ideas about code improvements, please, let me know. Any help is appreciated, thank you

I'm guessing you're missing the __enter__ function on that class. When you use a with block in Python, the __enter__ method of the object in the with statement is called, the block inside the with runs, and the __exit__ method is invoked. You'll get this error if your class doesn't have a __enter__ defined. so you have to define __enter__ method in your Booking class and return self in it

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)

This is the code I used and I run it without any issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM