Pass Proxy in Requests Python
If you want to use a proxy with your Python requests, you can pass it directly as a parameter when making the request. There are multiple ways to pass a proxy in requests Python, which we will discuss in detail below.
Using HTTP Proxy
If you want to use HTTP proxy with requests Python, you can do it by passing a dictionary with the URL of the proxy server to the proxies
parameter of the requests.get()
method.
import requests
# URL of the proxy server
http_proxy = "http://10.10.1.10:3128"
# Make a request using HTTP proxy
response = requests.get("http://www.google.com", proxies={'http': http_proxy})
print(response.content)
Using HTTPS Proxy
If you want to use HTTPS proxy with requests Python, you can do it by passing a dictionary with the URL of the proxy server to the proxies
parameter of the requests.get()
method, just like with HTTP proxy.
import requests
# URL of the proxy server
https_proxy = "https://10.10.1.10:1080"
# Make a request using HTTPS proxy
response = requests.get("https://www.google.com", proxies={'https': https_proxy})
print(response.content)
Using SOCKS Proxy
If you want to use SOCKS proxy with requests Python, you need to use a 3rd party library called socks
. Install it using pip:
pip install requests[socks]
Now, import the library and pass the URL of the SOCKS proxy server to the proxies
parameter of the requests.get()
method, along with a tuple containing the SOCKS protocol and the username and password for authentication (if required).
import requests
import socks
import socket
# Set the default socket to use SOCKS proxy
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "10.10.1.10", 1080)
# Set the default timeout for socket to 60 seconds
socket.socket = socks.socksocket
socket.setdefaulttimeout(60)
# Make a request using SOCKS proxy
response = requests.get("http://www.google.com")
print(response.content)
By default, SOCKS proxy does not require authentication. If your proxy server requires authentication, pass a tuple containing the username and password to the username
and password
parameters of the socks.setdefaultproxy()
method.
These are some ways of passing a proxy in requests Python. You can choose anyone according to your requirement and enjoy making requests with Python.