Last active
August 9, 2016 17:34
-
-
Save gaotongfei/2e37d97e93619c07d0b2910e3c4034e5 to your computer and use it in GitHub Desktop.
request with proxy
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
#coding:utf-8 | |
import requests | |
import time | |
from fake_useragent import UserAgent | |
import requests | |
requests.packages.urllib3.disable_warnings() | |
from random import randint | |
import socks | |
import socket | |
ua = UserAgent() | |
def rand_port(x, y, exclude): | |
r = None | |
while r in exclude or not r: | |
r = randint(x, y) | |
return r | |
def request_with_proxy(url, timeout=10, use_ss=False, sleep=10): | |
time.sleep(sleep) | |
headers = {'User-Agent': ua.random} | |
r = None | |
if not use_ss: | |
proxy_port = rand_port(9054, 9155, []) | |
proxies = { | |
"http": "socks5://127.0.0.1:{}".format(proxy_port), | |
"https": "socks5://127.0.0.1:{}".format(proxy_port) | |
} | |
r = requests.get(url, proxies=proxies, headers=headers, timeout=20) | |
else: | |
port_range = (1080, 1097) | |
error_ports = [1083, 1085, 1089, 1094] | |
port = rand_port(1080, 1097, error_ports) | |
proxies = { | |
"http": "socks5://127.0.0.1:{}".format(port), | |
"https": "socks5://127.0.0.1:{}".format(port) | |
} | |
r = requests.get(url, proxies=proxies, timeout=20, headers=headers) | |
return r |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment