如何验证Python3中requests.get()请求使用代理而非本地IP?
requests.get() is Using a Proxy Instead of Your Local IP Hey there! I get it—you want to make sure your requests.get() call is actually routing through the proxy you specified, not your local IP. Here are a few reliable ways to confirm this:
1. Check the Public IP Returned by a Service
The most straightforward method is to send a request to a service that returns your public IP address, like https://httpbin.org/ip. Compare the returned IP to your local public IP to verify the proxy is working.
Here's a code snippet to do this:
import requests # Your proxy configuration proxy_settings = {'https': 'x.x.x.x:xxxx'} # Note: If your proxy is an HTTP proxy (even for HTTPS requests), use 'http://x.x.x.x:xxxx' instead # Send request to httpbin to get the detected IP response = requests.get('https://httpbin.org/ip', proxies=proxy_settings) print("Detected IP:", response.json()['origin'])
- If the output matches your proxy's IP address (not your local public IP), the proxy is being used correctly.
- To find your local public IP, you can visit
https://httpbin.org/ipdirectly in your browser without the proxy.
2. Enable Debug Logging for Requests
You can turn on debug logging in the requests library to see exactly how your request is being routed. This will show you if the connection is being established through your proxy server.
Try this code:
import requests import logging # Enable debug-level logging logging.basicConfig(level=logging.DEBUG) proxy_settings = {'https': 'x.x.x.x:xxxx'} response = requests.get('https://example.com', proxies=proxy_settings)
Look for lines in the log output like:
DEBUG:urllib3.connectionpool:Starting new HTTPS connection to x.x.x.x:xxxx:443
DEBUG:urllib3.connectionpool:Starting new HTTP connection to x.x.x.x:xxxx:80
This confirms that the request is being sent through your proxy server. If you don't see references to your proxy IP in the logs, the proxy isn't being used.
3. Double-Check Your Proxy Configuration
A common mistake is incorrect proxy formatting:
- For HTTP proxies (used for both HTTP and HTTPS requests), the proxy URL should start with
http://(even when setting thehttpskey inproxies). For example:proxy_settings = {'https': 'http://x.x.x.x:xxxx'} - Make sure there are no typos in the proxy IP or port number.
内容的提问来源于stack exchange,提问作者chuck

