Python with statement (__enter__ and __exit__) 无法调用函数

Python with statement (__enter__ and __exit__) can't call function

我正在尝试使用 Python 3 创建一个带有 enterexit 函数的 Selenium 对象,这样我就可以按如下方式使用它:

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

但是,每当我尝试 运行 时,我都会收到以下错误:

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

有谁知道我做错了什么?下面是我的代码:

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))

您需要 return __enter__ 中的对象:

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

您现在正在 returning None(默认情况下),这意味着它正在尝试在 None 上调用 getURL(因为 browserNone 而不是您想要的 Browser 的实例)。