Created
September 19, 2018 11:13
-
-
Save dcragusa/d52f321d838de186fd2bd47dae281ee6 to your computer and use it in GitHub Desktop.
Get a requests session with proxy and appropriate user agent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
from requests.adapters import HTTPAdapter | |
PROXIES = { | |
'http': 'http://proxy.example.com:3128', | |
'https': 'https://proxy.example.com:3128' | |
} | |
class ProxyUAAdapter(HTTPAdapter): | |
def proxy_headers(self, proxy): | |
headers = super(ProxyUAAdapter, self).proxy_headers(proxy) | |
headers['User-Agent'] = 'Python' | |
return headers | |
def get_requests_session(proxies=None): | |
s = requests.Session() | |
s.mount('http://', ProxyUAAdapter()) | |
s.mount('https://', ProxyUAAdapter()) | |
if proxies is None: | |
proxies = PROXIES | |
s.proxies.update(proxies) | |
return s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment