Python 2 -> 3, urllib.urlOpen

Mark Lawrence breamoreboy at yahoo.co.uk
Sat Oct 14 15:25:06 EDT 2017


On 13/10/17 23:27, Irv Kalb wrote:
> One of the colleges where I teach has just moved from Python 2 to Python 3.  I am in the process of converting my beginning Python class from Python 2 to Python 3.  Everything has gone smoothly, until I just tried to convert some code that imports and uses urllib.urlOpen to fetch data through an API.  I am using an API that I found here:    http://www.jarloo.com/yahoo_finance/ <http://www.jarloo.com/yahoo_finance/>
> 
> As a minimal example, I am trying to get the latest stock price for Apple.
> 
> The following example works perfectly in Python 2:
> 
> import urllib
> 
> # set the Yahoo finance url, set stock name, ask for last price
> fullURLWithParameters = 'http://finance.yahoo.com/d/quotes.csv?s=aapl&f=l1'
> 
> # read all the data
> response = urllib.urlopen(fullURLWithParameters).read()
> 
> print 'Response is: ', response
> 
> This is asking for a stock name (s=) and I am adding in aapl as a stock symbol.  I am also adding a "flag" parameter (f=) and setting it to l1 to get the last trade price.  When I run this in Python 2, I see:
> 
> Response is:  156.99
> 
> 
> If I take the same program and just modify the print statement to add parentheses, then try to run it in Python 3.6 (on a Mac):
> 
> 
> import urllib
> 
> # set the Yahoo finance url, set stock name, ask for last price
> fullURLWithParameters = 'http://finance.yahoo.com/d/quotes.csv?s=aapl&f=l1'
> 
> # read all the data
> response = urllib.urlopen(fullURLWithParameters).read()
> 
> print('Response is: ', response)
> 
> I get the following:
> 
> Traceback (most recent call last):
>    File " ....  s/StockQuoteYahooAPIMinimal.py", line 9, in <module>
>      response = urllib.urlopen(fullURLWithParameters).read()
> AttributeError: module 'urllib' has no attribute 'urlopen'
> 
> 
> I've looked at the Python 3.6 documentation for urllib, and I see that certain calls have been changed and others have been eliminated.  But my eyes glaze over trying to figure out what to use instead.
> 
> My question is: Is there a simple (hopefully one or two line) replacement for my call to url lib.urlopen(<URL>).read()
> 
> I know that there are other modules out there that handle requests (like the Requests module), but this is a strictly controlled university environment.  I cannot download any external packages (other then pygame, which I got special permission for) onto the computers in the school.  Therefore, I'm looking for something in the Python 3.6 Standard Library.
> 
> Thanks in advance,
> 
> Irv
> 

Hopefully this https://docs.python.org/3/howto/pyporting.html will help.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list