【问题标题】:Python requests session does not rotate proxiesPython 请求会话不会轮换代理
【发布时间】:2021-03-30 08:24:06
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: python web-scraping python-requests ip proxies


    【解决方案1】:

    Session 使用之前为每个后续请求设置的变量/值,例如 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 等,因此您不应该使用会话。

    【讨论】:

    • 太好了,顺便说一句,为什么我们不应该保留 cookie,网站不需要 cookie。同样,当我尝试在没有会话的情况下发出请求时,它也不起作用,对于它提供验证码的每个请求。我在会话中使用相同的标题并且没有会话。
    • 如果您想维护 cookie/会话,轮换代理是没有意义的。该网站仍然可以识别您的身份。因此,只需使用常规会话而不更改代理。 (只使用一个或根本不使用。)
    • 欢迎来到 StackOverflow。阅读“What should I do when someone answers my question?”,了解VotingAccepting
    【解决方案2】:

    以下代码有效,它需要一个 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 站点并返回其真实 IP 以检查代理是否工作。 输出将类似于:

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

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

    http:1.1.1.1:3128
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2021-12-10
        • 2021-03-06
        • 2019-09-16
        • 1970-01-01
        • 2023-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多