opening a url with urllib in python 3 opening a url with urllib in python 3 python-3.x python-3.x

opening a url with urllib in python 3


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 urlopenwith urlopen("https://sunlightlabs.github.io/congress/legislators?api_key='(myapikey)") as conn:    # dosomething


In Python 3 You can implement that this way:

import urllib.requestu = 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 urlopenfrom bs4 import BeautifulSoupwiki = "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)