【问题标题】:Can't make use of proxies in the right way无法以正确的方式使用代理
【发布时间】:2018-10-15 15:00:02
【问题描述】:

我在 python 中编写了一个脚本来抓取通过代理生成的请求的 url。我在脚本中使用了shuffle() 来随机获取代理。该脚本在某种程度上做得很好。此脚本的问题是当它无法使用任何有效的代理时,由于循环,它会转到另一个 url。如何以这种方式纠正我的脚本,以便它会尝试使用列表中的每个代理(如果需要)来获取所有 urls

这是我的尝试:

import requests
from random import shuffle

url = "https://stackoverflow.com/questions?page={}&sort=newest"

def get_random_proxies():
    proxies = ['35.199.8.64:80', '50.224.173.189:8080', '173.164.26.117:3128']
    shuffle(proxies)
    return iter(proxies)

for link in [url.format(page) for page in range(1,6)]:
    proxy = next(get_random_proxies())
    try:
        response = requests.get(link,proxies={"http": "http://{}".format(proxy) , "https": "http://{}".format(proxy)})
        print(f'{response.url}\n{proxy}\n')
    except Exception:
        print("something went wrong!!" + "\n")
        proxy = next(get_random_proxies_iter())

我的输出:

https://stackoverflow.com/questions?page=1&sort=newest
35.199.8.64:80

https://stackoverflow.com/questions?page=2&sort=newest
50.224.173.189:8080

something went wrong!!

https://stackoverflow.com/questions?page=4&sort=newest
50.224.173.189:8080

something went wrong!!

您可以看到'page=3&sort=newest''page=5&sort=newest' 这两个网址没有响应,而我的两个代理仍在工作。

后记:它们是免费代理,所以我特意发布了它们。

【问题讨论】:

    标签: python python-3.x web-scraping proxy python-requests


    【解决方案1】:

    怎么样:

    def get_random_proxies():
        proxies = ['35.199.8.64:80', '50.224.173.189:8080', '173.164.26.117:3128']
        shuffle(proxies)
        return proxies
    
    for link in [url.format(page) for page in range(1,6)]:
        for proxy in get_random_proxies():
            try:
                response = requests.get(link,proxies={"http":proxy , "https": proxy})
                print(f'{response.url}\n{proxy}\n')
                break  # success, stop trying proxies
            except Exception:
                print("something went wrong!!" + "\n")
    

    我不确定return(iter(...))next(result) 的计划是什么,但更传统的方法是返回列表,然后根据需要循环遍历其中的一部分。您已经列出了清单,无需额外努力即可返回。

    【讨论】:

    • @Topto 第二个/内部 for 循环遍历 get_random_proxies() 的返回结果——所以遍历了洗牌的代理列表。在每次迭代中,它都会尝试通过代理访问链接。这种尝试可能会引发异常,如果出现异常,则会打印一条消息并继续循环。如果它没有引发,它会在try 块内继续,首先打印一条不同的消息,然后中断。 break 语句将中断到内部for 循环,这意味着不再尝试为此页面使用代理。外循环不受影响,其余页面将被获取
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    • 2019-02-10
    相关资源
    最近更新 更多