Замена модулей urllib2 запросами - PullRequest
0 голосов
/ 17 февраля 2019

Я пытаюсь получить живые данные об акциях и соответствующие им графики с использованием python.
В учебном пособии я узнал, что они используют urllib2, и через переполнение стека я узнал, что он приостановлен из-зак вопросам, и лучшая альтернатива - 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

1 Ответ

0 голосов
/ 20 февраля 2019

Вы не дали весь код, но что бы я ни интерпретировал, я его конвертирую.Нужно изменить только 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...