用请求替换urllib2模块

问题描述 投票:-1回答:1

我试图获取股票实时数据,并使用python绘制相应的图表。 在一个教程中我了解到他们正在使用urllib2and我通过堆栈溢出了解它因问题而被暂停,最好的选择是requests

以下是使用urllib2的代码段。请建议我requests的确切替代方案:

    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.x python-requests urllib2
1个回答
0
投票

你没有给出整个代码,但无论我解释什么,我都会转换它。您需要更改1或2行。代码在Python 3中。确保导入requests

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

© www.soinside.com 2019 - 2024. All rights reserved.