How to use proxy in Python Requests?
If you want to use a proxy server while making requests using Python Requests, you can do it easily by setting the proxies
parameter. This parameter takes a dictionary of proxy URLs keyed by their protocol (http, https, ftp, etc.).
Example using a single proxy:
import requests
proxies = {
'http': 'http://localhost:8080',
'https': 'https://localhost:8080'
}
response = requests.get('https://example.com', proxies=proxies)
In the example above, we set a single proxy server for both HTTP and HTTPS requests. Replace the proxy URL with your own proxy server URL and port number.
Example using different proxies for different protocols:
import requests
proxies = {
'http': 'http://localhost:8080',
'https': 'https://localhost:8080',
'ftp': 'ftp://localhost:8080'
}
response = requests.get('https://example.com', proxies=proxies)
In the example above, we set different proxy servers for HTTP, HTTPS, and FTP requests. Replace the proxy URLs with your own proxy server URLs and port numbers.
If you want to authenticate with your proxy server, you can add your username and password to the URL like this:
import requests
proxies = {
'http': 'http://username:password@localhost:8080',
'https': 'https://username:password@localhost:8080'
}
response = requests.get('https://example.com', proxies=proxies)
Replace the username
and password
with your own credentials and the proxy URL and port number with your own proxy server details.
That's it! Now you can use a proxy server while making requests using Python Requests.