Home > Software engineering >  Python Error: AttributeError: __enter__ using Selenium
Python Error: AttributeError: __enter__ using Selenium

Time:04-06

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!

CodePudding user response:

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

  • Related