You are reading the wrong documentation or the wrong Python interpreter version. You tried to use the Python 3 library in Python 2.
Use:
import urllib2
sock = urllib2.urlopen("http://diveintopython.org/")
htmlSource = sock.read()
sock.close()
print htmlSource
The Python 2 urllib2 library was replaced by urllib.request in Python 3.
You are reading the wrong documentation or the wrong Python interpreter version. You tried to use the Python 3 library in Python 2.
Use:
import urllib2
sock = urllib2.urlopen("http://diveintopython.org/")
htmlSource = sock.read()
sock.close()
print htmlSource
The Python 2 urllib2 library was replaced by urllib.request in Python 3.
In Python3 you can use urllib or urllib3
urllib:
import urllib.request
with urllib.request.urlopen('http://docs.python.org') as response:
htmlSource = response.read()
urllib3:
import urllib3
http = urllib3.PoolManager()
r = http.request('GET', 'http://docs.python.org')
htmlSource = r.data
More details could be found in the urllib or python documentation.
Videos
You need to use from urllib.request import urlopen, also I suggest you use the with statement while opening a connection.
from urllib.request import urlopen
with urlopen("https://sunlightlabs.github.io/congress/legislators?api_key='(myapikey)") as conn:
# dosomething
In Python 3 You can implement that this way:
import urllib.request
u = urllib.request.urlopen("xxxx")#The url you want to open
Pay attention:
Some IDE can import urllib(Spyder) directly, while some need to import urllib.request(PyCharm).
That's because you sometimes need to explicitly import the pieces you want, so the module doesn't need to load everything up when you just want a small part of it.
Hope this will help.