How to configure Python requests to use a proxy?

Python's requests package supports both HTTP and SOCKS5 proxies which can be set for each request or the whole script:

import requests

# proxy pattern is:
# scheme://username:password@IP:PORT
# For example:
# no auth HTTP proxy:
my_proxy = ""
# or socks5
my_proxy = "socks://"
# proxy with authentication
my_proxy = "http://my_username:my_password@"
# note: that username and password should be url quoted if they contain URL sensitive characters like "@":
from urllib.parse import quote
my_proxy = f"http://{quote('')}:{quote('password@123')}@"

proxies = {
    # this proxy will be applied to all http:// urls
    'http': '',
    # this proxy will be applied to all https:// urls (not the S)
    'https': '',
    # we can also use proxy only for specific pages
    '': '',
requests.get("", proxies=proxies)

Note that proxy can also be set through the standard *_PROXY environment variables:

$ export HTTP_PROXY=""
$ export HTTPS_PROXY=""
$ export ALL_PROXY="socks://"
$ python
import requests
# this will use the proxies we set

Finally, when web scraping using proxies we should rotate proxies for each request. See our how to rotate proxies guide for more. For more on proxies see introduction to proxies in web scraping

Question tagged: requests