urllib open url code example

Example 1: python open a url

import webbrowser

webbrowser.open('http://example.com')  # Go to example.com

Example 2: python how to get html code from url

import urllib.request		#pip install concat("urllib", number of current version)

my_request = urllib.request.urlopen("INSERT URL HERE")

my_HTML = my_request.read().decode("utf8")

print(my_HTML)

Example 3: urllib.request headers

try:
    from urllib.request import Request, urlopen  # Python 3
except ImportError:
    from urllib2 import Request, urlopen  # Python 2

req = Request('http://api.company.com/items/details?country=US&language=en')
req.add_header('apikey', 'xxx')
content = urlopen(req).read()

print(content)

Example 4: with urllib.request.urlopen("https://

import urllib.request

req = urllib.request.Request('http://www.voidspace.org.uk')
with urllib.request.urlopen(req) as response:
   the_page = response.read()

Example 5: urllib urlretrieve python 3

#In Python 3.x, the urlretrieve function is located in the urllib.request module:
from urllib.request import urlretrieve

Tags:

Html Example