Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

opening a url with urllib in python 3

Tags:

i'm trying to open the URL of this API from the sunlight foundation and return the data from the page in json. this is the code Ive produced, minus the parenthesis around myapikey.

import urllib.request.urlopen import json  urllib.request.urlopen("https://sunlightlabs.github.io/congress/legislators?api_key='(myapikey)") 

and im getting this error

Traceback (most recent call last):   File "<input>", line 1, in <module> ImportError: No module named request.urlopen 

what am i doing wrong? ive researched into https://docs.python.org/3/library/urllib.request.html and still no progress

like image 424
Bradley D. Freeman-Bain Avatar asked May 01 '16 10:05

Bradley D. Freeman-Bain


2 Answers

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 
like image 139
styvane Avatar answered Sep 18 '22 17:09

styvane


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.

like image 37
Lyn Avatar answered Sep 21 '22 17:09

Lyn