Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
To download a web page or a file over HTTP in Python, you can use the popular requests
library. The requests
library is not a part of the Python standard library, so you'll need to install it first, if you haven't already:
pip install requests
Here's an example of how to download a web page using the requests
library:
import requests # URL of the web page url = "https://example.com" # Send an HTTP GET request to the URL response = requests.get(url) # Check if the request was successful if response.status_code == 200: # Get the content of the web page content = response.text # Save the content to a file with open("web_page.html", "w", encoding=response.encoding) as file: file.write(content) print("Web page downloaded and saved as web_page.html") else: print(f"Failed to download the web page. Status code: {response.status_code}")
In this example, we use the requests.get()
function to send an HTTP GET request to the specified URL. The function returns a Response
object, which contains the HTTP status code, the content of the web page, and other information about the request. We check if the status code is 200 (indicating a successful request) and then save the content of the web page to a file.
Here's an example of how to download a file over HTTP using the requests
library:
import requests # URL of the file url = "https://example.com/path/to/your/file.txt" # Send an HTTP GET request to the URL response = requests.get(url) # Check if the request was successful if response.status_code == 200: # Save the file with open("downloaded_file.txt", "wb") as file: file.write(response.content) print("File downloaded and saved as downloaded_file.txt") else: print(f"Failed to download the file. Status code: {response.status_code}")
In this example, we use the same requests.get()
function to send an HTTP GET request to the specified file URL. After checking if the status code is 200, we save the content of the response (which is the file content) as a binary file using the write()
method of a file object opened in binary mode ("wb"
).
Note that these examples do not handle redirects, timeouts, and other potential issues that can occur during an HTTP request. Depending on your use case, you may want to add error handling and additional checks to make the download process more robust.