$0.00
A

Proxyvizr blog

How to use proxies in Python (requests and httpx)

In Python a proxy takes one line: requests and httpx accept the proxy address together with a username and password. Here is HTTP and SOCKS5, checking the connection and working with a proxy list.

Where to get the proxy details

Buy proxies in the Proxyvizr catalog or unified search and open "My proxies". Each proxy has a host:port:username:password line there, and traffic packages generate a list for the country you need on the same page. If your software needs another format, convert the list with the free Proxyvizr proxy converter.

HTTP proxy in requests

Pass the proxy for both schemes, http and https, or requests to HTTPS sites will go directly:

import requests
proxy = "http://LOGIN:PASSWORD@HOST:PORT"
proxies = {"http": proxy, "https": proxy}
r = requests.get("https://proxyvizr.com/api/my-ip", proxies=proxies, timeout=20)
print(r.json())

To check, request https://proxyvizr.com/api/my-ip: the response contains the IP and country that sites see.

SOCKS5 in requests

SOCKS5 needs an extra dependency. Use the socks5h scheme: the proxy then resolves domains, so DNS queries do not leak around it:

pip install "requests[socks]"
proxy = "socks5h://LOGIN:PASSWORD@HOST:PORT"
proxies = {"http": proxy, "https": proxy}

httpx

In httpx the proxy is set when creating the client. Newer versions call the parameter proxy, older ones proxies:

import httpx
with httpx.Client(proxy="http://LOGIN:PASSWORD@HOST:PORT", timeout=20) as client:
    print(client.get("https://proxyvizr.com/api/my-ip").json())

For SOCKS5 in httpx, install httpx[socks].

Proxy lists and rotation

If you have many proxies, keep them in a file, one per line, and pick an address per request or per session. For accounts keep one proxy per session; for scraping you can switch on every request. Residential traffic packages usually give one gateway address that rotates IPs itself, so you do not need a list.

Common mistakes

The proxy is set only for http, so HTTPS requests go directly. The username or password contains special characters that must be encoded (urllib.parse.quote). The socks5 scheme instead of socks5h, so DNS bypasses the proxy. No timeout, so the script hangs on a dead proxy.

Conclusion

In requests and httpx a proxy is one line. Set it for both http and https, use socks5h for SOCKS5 and always set a timeout.

Ready to pick your proxies?

Create an account in a minute and choose proxies for your task — residential, mobile, ISP, datacenter and SOCKS5 from trusted providers.