Import error: No module name urllib2 Import error: No module name urllib2 python python

Import error: No module name urllib2


As stated in the urllib2 documentation:

The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.

So you should instead be saying

from urllib.request import urlopenhtml = urlopen("http://www.google.com/").read()print(html)

Your current, now-edited code sample is incorrect because you are saying urllib.urlopen("http://www.google.com/") instead of just urlopen("http://www.google.com/").


For a script working with Python 2 (tested versions 2.7.3 and 2.6.8) and Python 3 (3.2.3 and 3.3.2+) try:

#! /usr/bin/env pythontry:    # For Python 3.0 and later    from urllib.request import urlopenexcept ImportError:    # Fall back to Python 2's urllib2    from urllib2 import urlopenhtml = urlopen("http://www.google.com/")print(html.read())


The above didn't work for me in 3.3. Try this instead (YMMV, etc)

import urllib.requesturl = "http://www.google.com/"request = urllib.request.Request(url)response = urllib.request.urlopen(request)print (response.read().decode('utf-8'))


matomo