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("(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 and still no progress

0

5 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("(myapikey)") as conn: # dosomething 
3

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.

from urllib.request import urlopen from bs4 import BeautifulSoup wiki = "" page = urlopen(wiki) soup = BeautifulSoup(page, "html.parser" ).encode('UTF-8') print (soup) 
1

urllib.request is a module whereas urlopen is a function. check out this link, it can help you clear your doubts.

1

The problem is with your module import. There are multiple ways to do that in Python3.x:

from urllib.request import urlopen urlopen(') 

or

from urllib import request request.urlopen(') 

or

import urllib urllib.request.urlopen(') 

Moreover, you can name the module you want to import as well:

import urllib.request as req ## or whatever you want req.urlopen(') 

You can use the one you prefer, but watch the sequence of modules and packages you are using.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy