![](/img/trans.png)
[英]Explaining Python's '__enter__' and '__exit__'
[英]Python with statement (__enter__ and __exit__) can't call function
我正在嘗試使用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))
您需要在__enter__
返回對象:
def __enter__(self):
"""Set things up"""
#Start the web driver
self.startDriver()
return self
現在,您將返回None
(默認情況下),這意味着它將嘗試在None
上調用getURL
(因為browser
為None
而不是您想要的Browser
實例)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.