Python 请求会话不轮换代理

Python requests session does not rotate proxies

我正在使用 (https://proxy.webshare.io/proxy/rotating?) 提供的私人轮换代理,其中轮换代理的每个请求都会收到一个新的 IP 地址。当我使用 requests.get('https://httpbin.org/get', headers=headers, proxies=get_proxy()) 每当我提出请求时,它 returns 都是一个新的 IP。但是当使用

session = requests.Session()
session.headers = headers
session.proxies = get_proxy()

session.get('https://httpbin.org/get')

它 returns 每次我发出请求时都是相同的 IP。 在代理的情况下,会话对象的行为与 requests.get() 函数有何不同。

Session 使用之前为每个后续请求设置的 variables/values,例如 Cookie。如果你想为会话中的每个请求更改代理,那么每次使用 Prepared Requests 设置它或者只是将它放在一个函数中:

def send(session, url):
    return session.get(url, proxy=get_proxy())

sess = requests.Session()
sess.headers = headers
resp = send(sess, 'https://httpbin.org/get')
print(resp.status_code)

但是,如果您试图隐藏原始 IP 以进行抓取或其他操作,您可能不希望 保留 cookie 等,因此您不应该使用会话.

以下代码有效,它需要一个 proxylistfile.txt 文件来检查每个代理:

from requests import *
import bs4 
import sys 

if len(sys.argv) < 2:
    print('Usage: ./testproxy.py <proxylistfile.txt>')
    sys.exit()

ifco = 'http://ifconfig.co'
PROXIES_FILE = sys.argv[1]
proxy = dict()

with open(PROXIES_FILE) as file:
    for line in file:
        if line[0] == '#' or line == "\n":
            continue
        line_parts = line.replace('\n', '').split(':')
        proxy['http'] = f'{line_parts[0]}://{line_parts[1]}:{line_parts[2]}'
        try:
            i = get(ifco, proxies=proxy, timeout=11)
            print(f"{proxy['http']} - successfull - IP ---> ", end='')
            zu = bs4.BeautifulSoup(i.text, 'html.parser')
            testo = zu.findAll('p', text=True)[0].get_text()
            print(testo)
        except:
            print(f"{proxy['http']} - unsuccessfull")
            pass
                     

它连接 ot ifconfig.co 站点和 return 它的真实 IP 以检查代理是否有效。 输出将类似于:

http://proxy:port - successfull - IP ---> your.real.ip

输入文件格式应该是这样的:

http:1.1.1.1:3128

我终于切换到另一个轮换代理提供商(https://www.proxyegg.com),现在问题已经解决了。