What is the urllib.request.urlopen() Method in Python

Python urllib.request.urlopen() method is “used for making GET requests.” The method returns a file-like object that you can use to read the URL’s content.

Syntax

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, 
                       capath=None, cadefault=False, context=None)

Parameters

The urllib.request module uses HTTP/1.1 and includes the Connection:close header in its HTTP requests.

The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This only works for HTTP, HTTPS, and FTP connections.

If the context is specified, it must be an SSL.SSLContext instance describing the various SSL options. See HTTPSConnection for more details.

The optional cafile and capath parameters specify a set of trusted CA certificates for HTTPS requests. cafile should point to a single file containing a bundle of CA certificates, whereas capath should point to a directory of hashed certificate files. More information can be found in SSL.SSLContext.load_verify_locations().

The cadefault parameter is ignored.

Example

import urllib.request

req_url = urllib.request.urlopen("https://appdividend.com")
print(req_url.read())

You can also use the with statement with the above code.

import urllib.request

with urllib.request.urlopen('https://appdividend.com') as response:
  html = response.read()
  print(html)

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.