-1

I want to create a bot using Python and Selenium. In my run.py file I want to be able to call all methods using that statement:

with Wikipedia as bot:
    bot.land_first_page()

In the class declaration I've included the functions enter() and exit() as below: Wikipedia.py

from selenium import webdriver
import Wiki.constants as const

class Wikipedia():
    def __init__(self, teardown=True, path_to_driver=const.PATH_TO_DRIVER):
        self.path = path_to_driver
        self.teardown = teardown

    def __enter__(self):
        self.driver = webdriver.Edge(self.path)
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.teardown:
            self.driver.quit()

    def land_first_page(self):
        self.driver.get(const.BASE_URL)

Other files: run.py

from Wiki.Wikipedia import Wikipedia

with BingTravel as bot:
    bot.land_first_page()

constants.py

BASE_URL = "https://www.wikipedia.org/"
PATH_TO_DRIVER = "C:\Program Files (x86)\edgedriver_win64\msedgedriver.exe"

However, I get this error all the time:

Traceback (most recent call last):
  File "D:Path\to\file\run.py", line 3, in <module>
    with Wikipedia as bot:
AttributeError: __enter__

I know that similar questions have already been asked, but unfortunately the proposed solutions did not work in my case

  1. Python with statement (__enter__ and __exit__) can't call function
  2. Object becomes None when using a context manager
  3. Python Error: AttributeError: __enter__
jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
Kacperom
  • 1
  • 2

0 Answers0