The urllib.request module in Python provides a higher-level interface for fetching URLs (Uniform Resource Locators) than the http module. It offers a simpler and more convenient way to make HTTP requests, handle redirections, and deal with common HTTP features like cookies and authentication.
Key features of the urllib.request module:
- urlopen(): A simple function for opening URLs and retrieving the response data.
- Request object: Provides more control over HTTP requests, allowing for setting headers, handling authentication, and sending custom data.
- urlopen() with context: Enables the use of context managers to customize the request behavior, such as setting timeouts and handling proxies.
- Cookie handling: Automatically manages cookies for HTTP requests, maintaining a persistent cookie jar across requests.
- Basic authentication: Supports basic authentication for accessing protected resources.
- Redirection handling: Automatically follows HTTP redirects to reach the final destination URL.
Make a POST request using the urllib.request module. It sends data to the “http://httpbin.org/post” URL and prints the response.
Import Statements
import urllib.request
import urllib.parse- Import Statements: Import the
urllib.requestandurllib.parsemodules for handling HTTP requests and encoding data.
Data Preparation for POST Request
data_dictionary = {"id": "0123456789"}
data = urllib.parse.urlencode(data_dictionary)
data = data.encode('ascii')- Data Dictionary: Creates a dictionary containing data for the POST request.
- URL Encoding: Uses
urllib.parse.urlencodeto convert the dictionary into a URL-encoded string. - Byte Encoding: Converts the string into bytes using
encode('ascii')to prepare it for sending in the POST request.
Making the POST Request
with urllib.request.urlopen("http://httpbin.org/post", data) as response:
print(response.read().decode('utf-8'))urlopenMethod: Opens the specified URL (“http://httpbin.org/post”) and sends the prepared data as a POST request.- Response Handling:
- Uses
response.read()to read the content of the response. decode('utf-8'): Decodes the response bytes into a UTF-8 string.- Prints the decoded response.
import urllib.request
import urllib.parse
#POST request
data_dictionary = {"id": "0123456789"}
data = urllib.parse.urlencode(data_dictionary)
data = data.encode('ascii')
with urllib.request.urlopen("http://httpbin.org/post", data) as response:
print(response.read().decode('utf-8'))The script demonstrates how to make a POST request using the urllib.request module. It prepares data in the form of a dictionary, encodes it, sends it to the specified URL, and prints the response received from the server. The http://httpbin.org/post URL is a testing service that echoes back the data it receives, making it useful for testing and debugging HTTP requests.
How to make an HTTP GET request to the “http://httpbin.org/get” URL using the urllib.request module. It then processes the JSON response and prints the decoded data.
Import Statements
import urllib.request
import json- Import Statements: Import the
urllib.requestmodule for making HTTP requests and thejsonmodule for handling JSON data.
URL for GET Request
url = "http://httpbin.org/get"- URL Definition: Specifies the URL (“http://httpbin.org/get”) to which the GET request will be made.
Making the GET Request
with urllib.request.urlopen(url) as response_json:
data_json = json.loads(response_json.read().decode("utf-8"))
print(data_json)urlopenMethod: Opens the specified URL (“http://httpbin.org/get”) and sends a GET request.- Response Handling:
response_json.read(): Reads the content of the response as bytes.decode("utf-8"): Decodes the bytes into a UTF-8 string.json.loads(): Parses the JSON-formatted string into a Python dictionary.- Prints the decoded JSON data.
The script makes an HTTP GET request to “http://httpbin.org/get” using the urllib.request module. It reads the response, decodes it as a UTF-8 string, and then uses the json module to parse the JSON-formatted string into a Python dictionary. Finally, it prints the decoded JSON data, demonstrating a simple way to interact with a web API and handle JSON responses in Python.
Get Response and Request Header
In the context of HTTP (Hypertext Transfer Protocol), a request header and a response header are additional pieces of information that accompany an HTTP request and response, respectively. They provide metadata about the request or response, enabling better communication between the client (web browser) and the server.
Request Headers
Request headers are sent by the client to the server along with the HTTP request. They provide information about the client’s capabilities, preferences, and the context of the request. Some common request headers include:
- User-Agent: Identifies the user agent (web browser or other application) making the request.
- Accept: Indicates the types of content formats (e.g., HTML, JSON) that the client can accept.
- Content-Type: Specifies the type of data being sent in the request body (e.g., text, form data).
- Authorization: Provides credentials for accessing protected resources.
- Referer: Indicates the URL of the page that linked to the current request.
Response Headers
Response headers are sent by the server to the client along with the HTTP response. They provide information about the response, such as the status code, content type, and server details. Some common response headers include:
- Content-Type: Specifies the type of data being sent in the response body (e.g., HTML, JSON).
- Content-Length: Indicates the size of the response body in bytes.
- Status Code: Provides a three-digit code indicating the outcome of the request (e.g., 200 for success, 404 for not found).
- Server: Identifies the web server software used to handle the request.
- Set-Cookie: Creates or modifies cookies on the client’s browser for future requests.
Significance of Request and Response Headers
Request and response headers play a crucial role in the efficient and effective communication between the client and server. They provide valuable information that enables:
- Content Negotiation: The client and server can negotiate the appropriate content format based on the Accept header.
- Authentication: Request headers like Authorization allow the client to provide credentials for accessing protected resources.
- Caching: Response headers like Cache-Control inform the client whether and how long to cache the response data.
- Error Handling: Status codes and related headers provide information about errors encountered during the request-response process.
- Debugging and Troubleshooting: Headers can be inspected to diagnose issues related to HTTP requests and responses.
Request and response headers are vital components of HTTP communication, providing contextual information that enhances the interaction between clients and servers. They facilitate content negotiation, authentication, caching, error handling, and debugging, ensuring seamless and efficient data exchange on the World Wide Web.
How to set a custom user agent (in this case, mimicking the Chrome browser’s user agent) for an HTTP request using the urllib.request module. It then prints the response headers received from the server and the request headers sent to the server.
Import Statements
import urllib.request
from urllib.request import Request- Import Statements: Import the necessary modules from
urllib.requestto handle HTTP requests.
URL and User Agent Definition
url = "https://awjunaid.com"
USER_AGENT = 'Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.101 Mobile Safari/537.36'- URL and User Agent Definition: Specifies the URL to make the HTTP request to (
http://python.org) and defines a custom user agent string mimicking Chrome on Android.
Function to Set Chrome User Agent
def chrome_user_agent():
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', USER_AGENT)]
urllib.request.install_opener(opener)
response = urllib.request.urlopen(url)- Opener Creation: Creates an opener using
urllib.request.build_opener()to set a custom user agent. - Setting User Agent: Adds the custom user agent to the opener’s headers.
- Installing Opener: Installs the custom opener.
- HTTP Request: Opens the URL using
urllib.request.urlopen().
Printing Response Headers
print("Response headers")
print("--------------------")
for header, value in response.getheaders():
print(header + ":" + value)- Printing Response Headers: Loops through the response headers and prints each header along with its value.
Creating Request with Custom User Agent
request = Request(url)
request.add_header('User-agent', USER_AGENT)- Request Creation: Creates a new request using
urllib.request.Request()for the same URL. - Setting User Agent in Request: Adds the custom user agent to the request headers.
Printing Request Headers
print("\nRequest headers")
print("--------------------")
for header, value in request.header_items():
print(header + ":" + value)- Printing Request Headers: Loops through the request headers and prints each header along with its value.
Main Block
if __name__ == '__main__':
chrome_user_agent()- Main Block: Calls the
chrome_user_agent()function when the script is executed.
#!/usr/bin/env python3
import urllib.request
from urllib.request import Request
url="https://awjunaid.com"
USER_AGENT = 'Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.101 Mobile Safari/537.36'
def chrome_user_agent():
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', USER_AGENT)]
urllib.request.install_opener(opener)
response = urllib.request.urlopen(url)
print("Response headers")
print("--------------------")
for header,value in response.getheaders():
print(header + ":" + value)
request = Request(url)
request.add_header('User-agent', USER_AGENT)
print("\nRequest headers")
print("--------------------")
for header,value in request.header_items():
print(header + ":" + value)
if __name__ == '__main__':
chrome_user_agent()Output
Response headers
--------------------
date:Thu, 16 Nov 2023 01:42:50 GMT
content-type:text/html; charset=UTF-8
transfer-encoding:chunked
vary:Accept-Encoding
cache-control:public, s-maxage=216000
server:Apache
x-content-security-policy:default-src 'self'; script-src 'self' https://hcaptcha.com https://*.hcaptcha.com; frame-src 'self' https://hcaptcha.com https://*.hcaptcha.com; style-src 'self' https://hcaptcha.com https://*.hcaptcha.com; connect-src 'self' https://hcaptcha.com https://*.hcaptcha.com; unsafe-eval 'self' https://hcaptcha.com https://*.hcaptcha.com; unsafe-inline 'self' https://hcaptcha.com https://*.hcaptcha.com;
link:<https://awjunaid.com/wp-json/>; rel="https://api.w.org/", <https://awjunaid.com/wp-json/wp/v2/pages/2172>; rel="alternate"; type="application/json", <https://wp.me/PeTdSC-z2>; rel=shortlink
x-stackcache-cacheable:yes
x-cache-enabled:true
x-provided-by:StackCDN
x-origin-cache-status:HIT
x-cdn-cache-status:HIT
x-via:MAD1
connection:close
Request headers
--------------------
User-agent:Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.101 Mobile Safari/537.36
The script demonstrates how to set a custom user agent for an HTTP request using urllib.request. It mimics the Chrome browser’s user agent, makes a request to “http://python.org,” and prints both the response headers received from the server and the request headers sent to the server. The user agent can be crucial for web scraping or making requests that mimic different browsers or devices.
Extracting Emails from a URL with urllib.request
Fetch and extract email addresses from the HTML content of a given URL. It sets a custom user agent, makes an HTTP request to the specified URL, retrieves the HTML content, and then uses a regular expression to find and print email addresses present in the HTML.
Import Statements
import urllib.request
import re- Import Statements: Import the required modules (
urllib.requestfor handling HTTP requests andrefor regular expressions).
User Agent and URL Input
USER_AGENT = 'Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.101 Mobile Safari/537.36'
url = input("Enter url:http://")- User Agent Definition: Specifies a custom user agent string mimicking Chrome on Android.
- URL Input: Takes user input for the URL, prefixed with “http://”.
Custom Opener with User Agent
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', USER_AGENT)]
urllib.request.install_opener(opener)- Custom Opener Setup: Creates an opener with the specified user agent and installs it globally.
HTTP Request to the Given URL
response = urllib.request.urlopen('http://'+url)
html_content= response.read()- HTTP Request: Opens the URL with the specified user agent and reads the HTML content from the response.
Regular Expression Pattern
pattern = re.compile("[-a-zA-Z0-9._]+[-a-zA-Z0-9._]+@[-a-zA-Z0-9_]+.[a-zA-Z0-9_.]+")
mails = re.findall(pattern, str(html_content))- Regular Expression Pattern: Defines a regular expression pattern to match email addresses in the HTML content.
- Finding Email Addresses: Uses
re.findall()to find all matches of the pattern in the HTML content.
Printing Extracted Email Addresses
print(mails)- Printing: Prints the list of email addresses extracted from the HTML content.
import urllib.request
import re
USER_AGENT = 'Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.101 Mobile Safari/537.36'
url = input("Enter url:http://")
https://awjunaid.com/terms-conditions/
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', USER_AGENT)]
urllib.request.install_opener(opener)
response = urllib.request.urlopen('http://'+url)
html_content= response.read()
pattern = re.compile("[-a-zA-Z0-9._]+[-a-zA-Z0-9._]+@[-a-zA-Z0-9_]+.[a-zA-Z0-9_.]+")
mails = re.findall(pattern,str(html_content))
print(mails)This script is designed to extract email addresses from the HTML content of a given URL. It sets a custom user agent, performs an HTTP request, retrieves the HTML, applies a regular expression pattern to identify email addresses, and finally prints the extracted email addresses. Keep in mind that using regular expressions for parsing HTML can be fragile, and more robust solutions like HTML parsers are recommended for complex scenarios.
Download Files with urllib.request
Download an image file (Python logo) from a given URL using two different methods: urllib.request.urlretrieve and urllib.request.urlopen. It saves the downloaded image as “python.png.”
Import Statement
import urllib.request- Import Statement: Imports the
urllib.requestmodule for handling URL-related operations.
Starting the Download
print("starting download....")- Print Statement: Displays a message indicating the start of the download process.
URL for Image Download
url = "https://www.python.org/static/img/python-logo.png"- URL Definition: Specifies the URL of the image file (Python logo) to be downloaded.
Downloading with urllib.request.urlretrieve
# download file with urlretrieve
urllib.request.urlretrieve(url, "python.png")- Downloading with
urlretrieve: - Uses
urllib.request.urlretrieveto download the image file. - Saves the downloaded file as “python.png.”
Downloading with urllib.request.urlopen
# download file with urlopen
with urllib.request.urlopen(url) as response:
print("Status:", response.status)
print("Downloading python.png")
with open("python.png", "wb") as image:
image.write(response.read())- Downloading with
urlopen: - Uses
urllib.request.urlopento open the URL and get the response. - Prints the HTTP status of the response.
- Reads the content of the response and writes it to a local file (“python.png”) in binary mode (
"wb").
#!/usr/bin/python
import urllib.request
print("starting download....")
url="https://www.python.org/static/img/python-logo.png"
#download file with urlretrieve
urllib.request.urlretrieve(url, "python.png")
#download file with urlopen
with urllib.request.urlopen(url) as response:
print("Status:", response.status)
print( "Downloading python.png")
with open("python.png", "wb" ) as image:
image.write(response.read())The script demonstrates two methods for downloading an image file from a URL using the urllib.request module. It first uses urlretrieve to directly download and save the image, and then it uses urlopen to open the URL, read the content, and save it to a local file. The script is a basic example of downloading files from the web in Python.
Handling Exceptions with urllib.request
Defines a function, count_words_file(url), which attempts to open and read the content of a file from a given URL. It then counts the number of words in the content using the split() method. The code also includes error handling to catch URLError exceptions and print information about the error.
Import Statements
import urllib.request
import urllib.error- Import Statements: Import the necessary modules from
urllib.requestandurllib.errorfor handling HTTP requests and errors.
Function for Counting Words in a File
def count_words_file(url):
try:
file_response = urllib.request.urlopen(url)
except urllib.error.URLError as error:
print('Exception', error)
print('Reason:', error.reason)
else:
content = file_response.read()
return len(content.split())- Function Definition (
count_words_file): - Takes a URL as a parameter.
- Tries to open the URL using
urllib.request.urlopen. - Catches and handles
URLErrorexceptions, printing the exception and its reason. - If the URL is successfully opened, reads the content and returns the count of words in the content using
len(content.split()).
Example Usage
print(count_words_file('https://www.gutenberg.org/cache/epub/2000/pg2000.txt'))- Example Usage 1:
- Calls the
count_words_filefunction with a URL pointing to a text file on Project Gutenberg. - Prints the count of words in the content of the file.
count_words_file('https://not-exists.txt')- Example Usage 2:
- Calls the
count_words_filefunction with a URL that does not exist ('https://not-exists.txt'). - Triggers a
URLError, and the exception details are printed.
#!/usr/bin/env python3
import urllib.request
import urllib.error
def count_words_file(url):
try:
file_response = urllib.request.urlopen(url)
except urllib.error.URLError as error:
print('Exception', error)
print('reason', error.reason)
else:
content = file_response.read()
return len(content.split())
print(count_words_file('https://www.gutenberg.org/cache/epub/2000/pg2000.txt'))
count_words_file('https://not-exists.txt')The script defines a function to count words in the content of a file retrieved from a given URL. It demonstrates error handling for URLError exceptions when attempting to open a URL. The examples showcase the function’s usage with both a valid URL and a non-existent URL, highlighting the error-handling mechanism.
