1

I'm trying to use Python 3 to create a Selenium object with enter and exit functions so I can use it as follows:

with Browser() as browser:
    brower.getURL('http://www.python.org')

However, whenever I try to run this I get the following error:

Traceback (most recent call last):
  File "browser.py", line 54, in <module>
    print(browser.getURL(url))
AttributeError: 'NoneType' object has no attribute 'getURL'

Does anyone know what I am doing wrong? Below is my code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os

CHROMEBROWSERLOCATION = './drivers/chromedriver'

class Browser(object):
    """Handles web browser"""
    def __init(self):
        """Class Initialization Function"""

    def __call__(self):
        """Class call"""

    def startDriver(self,browser="chrome"):
        """Starts the driver"""
        #Make sure that the browser parameter is a string
        assert isinstance(browser,str)

        #Standardize the browser selection string
        browser = browser.lower().strip()
        #Start the browser
        if browser=="chrome":
            self.driver = webdriver.Chrome(CHROMEBROWSERLOCATION)

    def closeDriver(self):
        """Close the browser object"""
        #Try to close the browser
        try:
            self.driver.close()
        except Exception as e:
            print("Error closing the web browser: {}".format(e))

    def getURL(self,url):
        """Retrieve the data from a url"""
        #Retrieve the data from the specified url
        data = self.driver.get(url)

        return data

    def __enter__(self):
        """Set things up"""
        #Start the web driver
        self.startDriver()

    def __exit__(self, type, value, traceback):
        """Tear things down"""
        #Close the webdriver
        self.closeDriver()

if __name__ == '__main__':
    url = 'http://www.python.org'
    with Browser() as browser:
        print(browser.getURL(url))
user2694306
  • 3,610
  • 9
  • 40
  • 85

1 Answers1

4

You need to return the object in __enter__:

def __enter__(self):
    """Set things up"""
    #Start the web driver
    self.startDriver()
    return self

You're now returning None (by default) and that means it's trying to call getURL on None (because browser is None and not the instance of Browser that you intended).

Simeon Visser
  • 113,587
  • 18
  • 171
  • 175