In web development, data scraping, and automation testing, HTTP POST requests play a crucial role in “sending data to servers”—a key difference from GET requests, which only retrieve data. Whether you’re simulating a user login, submitting a form, or interacting with a web API, mastering POST requests in Python is essential. This tutorial uses a local WordPress login scenario to walk you through the entire process: from preparing parameters to writing code, sending requests, and saving server responses. Even if you’re new to Python, you’ll be able to follow along with detailed steps.
1. Understand the Basics: What Is an HTTP POST Request?
Before writing code, it’s important to clarify the purpose and logic of POST requests, as this forms the foundation for subsequent operations.
- Core Function of POST Requests: Unlike GET requests (which only “read” data from servers), POST requests are designed to “submit data” to servers. Common use cases include logging in with a username and password, submitting a registration form, or uploading a file.
- Tutorial Scenario: We’ll use a local WordPress admin login page (typically `http://localhost/wp-login.php`) as our test case. Our goal is to: 1) Send a username and password to the WordPress server via a POST request; 2) Receive the server’s response (e.g., an error message for an incorrect password); 3) Save the response to a local file for later review.
- Required Tools & Libraries: Ensure you have Python installed on your computer. We’ll use two key libraries: `urllib3` (for sending HTTP requests) and `sys` (for handling command-line arguments). Install `urllib3` via the command: `pip install urllib3`.
2. Critical Preparation: Get Form Submission Parameters
To simulate form submission, you first need to know the “parameter names” the form uses to send data to the server (e.g., is the username parameter called `log` or `username`?). You can find these names using your browser’s developer tools, following these steps:
- Open your local WordPress login page in Chrome or Edge. Right-click the “Username” input field and select “Inspect” to open the developer tools.
- In the “Elements” tab of the developer tools, locate the HTML code for the username input field. Look for the `name` attribute—you’ll see `name=”log”`. This means the parameter name for the username is `log`.
- Repeat the process for the “Password” input field. You’ll find its `name` attribute is `name=”pwd”`, so the parameter name for the password is `pwd`.
- Record these two parameter names (`log` and `pwd`). They are critical for writing code—if you use the wrong names, the server won’t recognize the data you submit.
3. Write the Code: Implement the Full POST Request Flow
This is the core section of the tutorial. We’ll break the code into 5 clear steps, with explanations for each line, so you understand exactly what each part does.
Step 1: Import Libraries and Define the Core Function
First, import the `urllib3` and `sys` libraries. Then, define a function called `post_request` that will handle parameter reception, request sending, and result return.
# Import urllib3 for HTTP requests and sys for command-line arguments
import urllib3
import sys
# Define the POST request function with 3 parameters: target URL, username, password
def post_request(url, username, password):
# Code for subsequent steps will go here
pass
Step 2: Package the Data to Be Submitted
Inside the `post_request` function, use a Python dictionary to package the data you want to submit. The “keys” of the dictionary must match the parameter names you found earlier (`log` and `pwd`), and the “values” will be the actual username and password.
# Package submission data: keys = form parameter names, values = actual data
data = {
"log": username, # Matches the "name" attribute of the username field ("log")
"pwd": password # Matches the "name" attribute of the password field ("pwd")
}
Step 3: Create a Connection Pool and Send the POST Request
Use `urllib3`’s `PoolManager` to create a connection pool (this improves efficiency by avoiding repeated connection creation). Then, call the `request` method to send the POST request, specifying the request method, target URL, and packaged data.
# Disable SSL certificate verification warnings (safe for local testing; enable for production)
urllib3.disable_warnings()
# Create a connection pool manager to send HTTP requests
http = urllib3.PoolManager()
# Send the POST request: 1st arg = request method ("POST"), 2nd arg = target URL, 3rd arg = submission data
resp = http.request(
"POST",
url,
fields=data
)
Step 4: Retrieve the Server Response and Save It to a File
After sending the request, the server will return a response. Use `resp.data` to get the response data (decode it to a string), print the result to the console for real-time checking, and then write the result to a local file (e.g., `login_result.html`).
# Get the server response: decode binary data to a UTF-8 string
response_data = resp.data.decode("utf-8")
# Print the result to the console for immediate verification
print("Server Response:\n", response_data)
# Save the response to a local HTML file (easy to open and view later)
with open("login_result.html", "w", encoding="utf-8") as file:
file.write(response_data)
# Return the response data for potential use in other parts of the code
return response_data
Step 5: Pass Arguments via Command Line and Call the Function
Finally, use `sys.argv` to get arguments passed from the command line (URL, username, password), and call the `post_request` function to execute the full flow.
# Main program entry: get arguments from the command line (order: script name, URL, username, password)
if __name__ == "__main__":
# Extract arguments: sys.argv[0] = script name, sys.argv[1:] = actual input arguments
target_url = sys.argv[1]
user_name = sys.argv[2]
user_password = sys.argv[3]
# Call the POST request function to run the full process
post_request(target_url, user_name, user_password)
# Print a completion message to confirm success
print("Request completed! Response saved to login_result.html")
4. Run and Verify: Ensure the Code Works Correctly
After writing the code, you need to run it via the command line and verify the results to ensure the entire flow works as expected. Follow these steps:
- Save the Code: Save the complete code above as `python_post_demo.py` in the `C:\work` directory (or any directory you prefer).
- Open the Command Line: Press `Win+R`, type `cmd`, and press Enter. Use the command `cd C:\work` to navigate to the directory where your code is saved.
- Execute the Command: Enter the command:
`python python_post_demo.py http://localhost/wp-login.php test 111111` ''' Here: - `http://localhost/wp-login.php` is the URL of your local WordPress login page; - `test` is the username you want to submit; - `111111` is the password (we’ll use an incorrect password to test the error response). '''
- Verify the Results:
– The console will print the HTML code returned by the server, including an error message like “The password you entered for the username test is incorrect.”;
– A file named `login_result.html` will be created in the `C:\work` directory. Open this file in a browser—you’ll see the exact same error page as when you manually enter an incorrect password on the WordPress login page.
5. Troubleshoot Common Issues
You may encounter some problems during execution. Below are 2 common issues and their solutions to help you quickly resolve errors:
- Issue 1: “No module named ‘urllib3′” Error
Solution: Open the command line and run `pip install urllib3` to ensure the library is installed. If the error persists, check if your Python environment variables are configured correctly. - Issue 2: Server Returns “404 Not Found” or “Connection Refused”
Solution: First, confirm your local WordPress server is running. Then, check if the URL you passed in the command line is correct (e.g., no extra slashes or missing paths). Ensure the URL opens normally in a browser.
6. Demo Video
You can watch the following demo video by select the subtitle to your preferred subtitle language.