Simple demo
urllib.requests.urlretrieve downloads the content of a URL to a file.
import urllib.request
url = 'https://raw.githubusercontent.com/ReneNyffenegger/about-python/master/standard-library/urllib/request/demo.py'
html_text = urllib.request.urlopen(url).read()
#
# The type of html_text is 'bytes'
#
print(html_text.decode('utf-8'))
urllib.request.urlretrieve (url, 'downloaded-script.py');
Exception for urlopen
urlopen raises urllib.error.URLError if something goes wrong:
try:
res = urllib.request.urlopen('https://domain-does-not-exi.st/')
except urllib.error.URLError as e:
print(e.reason)
urllib.error.HTTPError allows to filter for more specific errors;
try:
res = urllib.request.urlopen('https://renenyffenegger.ch/does-not-exist')
except urllib.error.HTTPError as e:
print(e.reason)