Python 3.x 用请求替换urllib2模块
我正在尝试获取stocks live数据,并使用python绘制与之对应的图表。Python 3.x 用请求替换urllib2模块,python-3.x,python-requests,urllib2,Python 3.x,Python Requests,Urllib2,我正在尝试获取stocks live数据,并使用python绘制与之对应的图表。 在一个教程中,我了解到他们使用的是urllib2,我通过堆栈溢出了解到,它由于问题而被挂起,最好的替代方法是请求 下面是使用urllib2的代码段。请为我推荐请求的确切替代方案: def GetQuote(self, symbols=['AAPL','GOOG']): '''This method gets a real-time stock quote from the nasdaq websit
在一个教程中,我了解到他们使用的是
urllib2
,我通过堆栈溢出了解到,它由于问题而被挂起,最好的替代方法是请求
下面是使用urllib2
的代码段。请为我推荐请求的确切替代方案
:
def GetQuote(self, symbols=['AAPL','GOOG']):
'''This method gets a real-time stock quote from the nasdaq website.'''
# Make sure the quoteList is a list
if type(symbols) != type([]):
symbols = [symbols]
# Create a string with the list of symbols
symbolList = ','.join(symbols)
# Create the full query
url = self.kBaseURI % symbolList
# Make sure the URL is formatted correctly
self.url = urllib2.quote(url, safe="%/:=&?~#+!$,;'@()*[]")
# Retrieve the data
urlFile = urllib2.urlopen(self.url)
self.urlData = urlFile.read()
urlFile.close()
# Parse the returned data
quotes = self._ParseData(self.urlData)
return quotes
您还没有给出完整的代码,但是无论我解释什么,我都会转换它。只有一两行需要更改。代码是用Python 3编写的。确保导入
请求
def GetQuote(self, symbols=['AAPL','GOOG']):
'''This method gets a real-time stock quote from the nasdaq website.'''
# Make sure the quoteList is a list
if type(symbols) != type([]):
symbols = [symbols]
# Create a string with the list of symbols
symbolList = ','.join(symbols)
# Create the full query
url = self.kBaseURI % symbolList
# Make sure the URL is formatted correctly
self.url = requests.utils.requote_uri(url)
# Retrieve the data
urlFile = requests.get(self.url)
self.urlData = urlFile.content
# Parse the returned data
quotes = self._ParseData(self.urlData)
return quotes