Python 2 -> 3, urllib.urlOpen

Thomas Jollans tjol at tjol.eu
Fri Oct 13 18:47:42 EDT 2017


On 14/10/17 00: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/>
> 

Hi Irv,

That's great! It's always nice to hear about more people moving with the
times :-)

> [...]
>
> 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()

Python 3 changed a number of things, including some rearrangement of the
standard library. The "What's new in Python 3.x" documents are always
worth reading, but I think you'll find "What's new in Python 3.0"
particularly useful. <https://docs.python.org/3/whatsnew/3.0.html>

The library changes are specified in PEP 3108 (this is linked from the
"What's new" document) <https://www.python.org/dev/peps/pep-3108/>

Python 3 has the urllib.request.urlopen function
<https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen>
- this is descended from Python 2's urllib2.urlopen, and should be
exactly what you need.

> 
> 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.  

It's nice that Python comes with batteries included, isn't it?


Cheers,
Thomas


PS: Pay attention to the fact that Python is case sensitive, and the
function called urlopen (like in your code) and not urlOpen (like in
your subject line)



More information about the Python-list mailing list