【问题标题】:Python Concurent Future, Each Thread, Each ProxyPython并发Future,每个线程,每个代理
【发布时间】:2021-10-26 14:36:00
【问题描述】:

所以我有这样的代码:

网站列表

a.com
b.com
c.com
d.com
e.com
etc

代理列表

1.1.1.1
2.2.2.2
etc
def extract(url, proxy):
    print(f'Thread Name : {threading.current_thread().name}')
    print(f'We are using this proxy : {proxy}')
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0'}
    try:
        r = requests.get(url, headers=headers, proxies={'http' : proxy,'https': proxy}, timeout=2)
        soup = BeautifulSoup(r.text, 'html.parser')
        page_title = soup.find('title').text.strip()
        print(page_title)
     except:
        pass

我需要循环提取函数,直到列表中的所有站点都完成..据我所知,python 中有concurent.futures,所以我在这里尝试:

with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
    executor.map(extract, url_list, proxy_list)

问题是,假设我只有 2 个有效代理,而我有 5 个站点,代码将停止在 2 个代理中,

如何解决这个问题?所以我想要的是每个线程都有自己的代理,并完成任务,直到列表中的所有站点都完成..

谢谢

【问题讨论】:

    标签: python multithreading beautifulsoup proxy python-requests


    【解决方案1】:

    使用itertools.cycle 创建一个迭代器,无限期地重复您的代理

    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
        executor.map(extract, url_list, itertools.cycle(proxy_list))
    

    【讨论】:

    • 谢谢.. 这就是答案.. 但如果下一个代理不起作用,我们想更改为好的代理,我们可以使用 itertools 处理这个问题吗?
    猜你喜欢
    • 2018-10-27
    • 2021-10-18
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 2012-08-20
    相关资源
    最近更新 更多