Python 2 -> 3, urllib.urlOpen
Irv Kalb
Irv at furrypants.com
Fri Oct 13 18:27:51 EDT 2017
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
More information about the Python-list
mailing list