Opening url with urllib in python 3

I am trying to open the URL of this API from a base of sunlight and return the data from the page in json. this is the code that Ive created, minus the parentheses around myapikey.

import urllib.request.urlopen
import json

urllib.request.urlopen("https://sunlightlabs.imtqy.com/congress/legislators?api_key='(myapikey)")

and im get 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 at https://docs.python.org/3/library/urllib.request.html and still no progress

+4
source share
4 answers

You need to use from urllib.request import urlopen, also I suggest you use the instruction withwhen opening a connection.

from urllib.request import urlopen

with urlopen("https://sunlightlabs.imtqy.com/congress/legislators?api_key='(myapikey)") as conn:
    # dosomething
+6
source

In Python 3, you can implement this as follows:

import urllib.request
u = urllib.request.urlopen("xxxx")#The url you want to open

: IDE import urllib (Spyder), - import urllib.request (PyCharm).

, , , .

, .

+4
from urllib.request import urlopen
from bs4 import BeautifulSoup

wiki = "https://en.wikipedia.org/wiki/List_of_state_and_union_territory_capitals_in_India"

page = urlopen(wiki)
soup =  BeautifulSoup(page, "html.parser" ).encode('UTF-8')

print (soup)
+1
source

urllib.requestis a module, while urlopenis a function. check this link, it will help you eliminate your doubts. https://docs.python.org/3.0/library/urllib.request.html

0
source

All Articles