带语句的Python(__enter __和__exit__)无法调用函数

时间:2015-12-31 17:14:59

标签: python selenium with-statement

我尝试使用Python 3创建一个带有输入退出功能的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))

1 个答案:

答案 0 :(得分:3)

您需要在__enter__中返回对象:

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

您现在正在返回None(默认情况下),这意味着它正试图在getURL上致电None(因为browserNone而不是您想要的Browser实例。