如何使用Requests实现文件上传?已有Selenium上传成功代码
使用Requests实现文件上传(替代Selenium方案)
Hey there! Let's turn your Selenium file upload workflow into a working Requests solution. Your Selenium code works because it simulates a user selecting a file via the browser's native file picker, but with Requests we need to directly construct the HTTP request that the browser sends when that file is uploaded.
First, let's recap what your Selenium code does:
- It loads the target page, finds the
<input type="file">element, sends your local file path to it, then grabs the result text from theoutput#resultelement.
The key issue with your initial Requests code:
You used a GET request, but file uploads almost always rely on a POST request with the multipart/form-data content type. We need to replicate that properly to get the expected result.
Step-by-step solution:
- Find the actual upload endpoint: Use your browser's DevTools (Network tab) to capture the request that fires when you upload a file via Selenium. Look for a
POSTrequest carrying your file data—this is the URL you'll use with Requests. - Identify the form field name: Check the
nameattribute of the<input type="file">element (e.g., if it's<input type="file" name="user_upload">, the field name isuser_upload). - Construct the Requests upload request: Use the
filesparameter inrequests.post()to package and send your file.
Working code example:
import requests from lxml import html # Replace these with your actual values file_path = r'C:\abc.jpg' upload_url = 'https://www.example.com/actual-upload-endpoint' # Captured from DevTools file_field_name = 'file' # Matches the input's name attribute # Use a session to maintain cookies (critical for logged-in sites or session-dependent uploads) session = requests.Session() # Optional: Load the upload page first to grab necessary cookies/tokens # session.get('https://www.example.com') # Prepare and send the upload request with open(file_path, 'rb') as file: files = { file_field_name: ('abc.jpg', file, 'image/jpeg') # (filename, file object, content type) } response = session.post(upload_url, files=files) # Parse the response to get the result (mirroring your Selenium logic) tree = html.fromstring(response.content) result_text = tree.xpath("//output[@id='result']/text()")[0] print(result_text)
Important notes to avoid issues:
- Always use the correct upload URL: Don't assume it's the same as the page URL—many sites use a dedicated AJAX endpoint for file uploads.
- Match the form field name exactly: If you use the wrong name, the server won't recognize your uploaded file.
- Handle sessions/cookies: If the site requires authentication or maintains session state,
requests.Session()will persist cookies between requests for you. - Content type: For images, use
image/jpegorimage/png; if you're unsure, you can omit this value and Requests will auto-detect it.
内容的提问来源于stack exchange,提问作者Chan
相关产品推荐
相关产品推荐

