Python中使用requests发送POST请求时如何指定id属性作为参数键
Great question—let’s break this down and get you the solution you need.
First, a quick reality check: When browsers submit forms, they only send parameters using the name attribute of form elements—the id is just for client-side use (like styling or JavaScript) and isn’t included in the request by default. That means if you send {'input1':'myuser', 'input2':'mypw'} directly, the server will almost certainly ignore those values, since it’s expecting keys like username and password (matching the name attributes in your HTML).
But if you want to work with IDs in your code while still sending the server the correct name-based keys, here’s how to do it:
Option 1: Manual ID-to-Name Mapping (Static Forms)
If you know the form structure upfront, create a simple mapping dictionary to translate IDs to their corresponding name values, then convert your ID-based input to server-friendly data:
Define the ID → Name mapping:
id_to_name = { 'input1': 'username', 'input2': 'password' }Create your input using IDs as keys:
user_credentials = { 'input1': 'myuser', 'input2': 'mypw' }Convert to server-compatible data:
post_data = {id_to_name[id_key]: value for id_key, value in user_credentials.items()}Send the request:
import requests loginUrl = "http://mylogin.net" r = requests.post(loginUrl, data=post_data)
Option 2: Dynamic Mapping (For Crawling/Changing Forms)
If you’re scraping the page and need to handle dynamic forms automatically, use a parser like BeautifulSoup to extract the ID-to-Name mapping directly from the HTML:
from bs4 import BeautifulSoup import requests # Fetch the login page first to get the form details login_page = requests.get("http://mylogin.net") soup = BeautifulSoup(login_page.text, 'html.parser') # Locate the login form login_form = soup.find('form', {'name': 'login'}) # Build the ID-to-Name mapping automatically id_to_name = {} for input_field in login_form.find_all('input', {'name': True}): if input_field.get('id'): # Only include fields with an ID id_to_name[input_field['id']] = input_field['name'] # Your ID-based input user_credentials = { 'input1': 'myuser', 'input2': 'mypw' } # Convert and send the request post_data = {id_to_name[id_key]: value for id_key, value in user_credentials.items()} r = requests.post(loginUrl, data=post_data)
A Quick Note on Edge Cases
If by some rare chance the server does expect IDs as parameter keys (this is extremely unusual—most backend frameworks are built to use name attributes), you can skip the mapping entirely and send your ID-based dictionary directly:
r = requests.post(loginUrl, data={'input1':'myuser', 'input2':'mypw'})
But 99% of the time, the mapping step is necessary to ensure the server processes your request correctly.
内容的提问来源于stack exchange,提问作者Ingo

