我尝试使用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))
答案 0 :(得分:3)
您需要在__enter__
中返回对象:
def __enter__(self):
"""Set things up"""
#Start the web driver
self.startDriver()
return self
您现在正在返回None
(默认情况下),这意味着它正试图在getURL
上致电None
(因为browser
是None
而不是您想要的Browser
实例。