【问题标题】:Python with statement (__enter__ and __exit__) can't call functionPython with statement (__enter__ and __exit__) 不能调用函数
【发布时间】:2015-12-31 17:14:59
【问题描述】:

我正在尝试使用 Python 3 创建一个带有 enter 和 exit 函数的 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))

【问题讨论】:

    标签: python selenium with-statement


    【解决方案1】:

    需要返回__enter__中的对象:

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

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

    【讨论】:

    • 顺便说一句...(应该没有任何区别,因为它是空的,但是)可能__init 本来是__init__
    猜你喜欢
    • 2016-03-08
    • 2019-12-01
    • 2010-12-31
    • 2016-10-31
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    相关资源
    最近更新 更多