首页 > 解决方案 > python请求和concurrent.futures的问题

问题描述

代码:

with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor:
    for i in range(r):
        processes.append(executor.submit(scrape, i))
    for _ in concurrent.futures.as_completed(processes):
        offers += _.result()
        print('total:', len(offers))

刮擦功能看起来像这样:

def scrape(i):
    requests.get(f'somepage.com/page{i}')
    //use bs4 to get the offers
    print(len(offers))
    return offers

我有这段代码设置。scrape 函数抓取具有页面 i 的网站,并返回提供的链接列表。此函数还打印列表的长度,仅用于调试目的。当我运行我的代码时,前几页运行良好,打印总:len(offers),但之后它不运行“总:”打印,只在刮功能中打印。这是输出。预期的输出将类似于

total: 120
120
total: 240
120
total: 360

等等

我很乐意接受任何帮助,这是我第一次在 python 中处理并发的东西,也是第一次使用堆栈溢出来提问。

标签: pythonconcurrent.futures

解决方案


也许这会帮助你理解线程。

每个线程将花费自己的处理时间,并在完成后返回。所以你不会看到像print(len(offers))then这样的顺序结果print('total:', len(offers))
只是为了测试这一点,假设我们删除请求并进行如下调整:

import concurrent.futures
r=10
processes=[]
offers=""
with concurrent.futures.ThreadPoolExecutor(max_workers=6) as executor:
    for i in range(r):
        processes.append(executor.submit(scrape, i))
    for _ in concurrent.futures.as_completed(processes):
        offers += _.result()
        #print('total:', len(offers))
        print('total:', offers)
        print("*****")

def scrape(i):
    print(f"scrape {i}")
    return f"scrape return {i}"

您会注意到print(f"scrape {i}")在处理过程中很早就已处理,然后得到print('total:', offers).

在这种类型的设置中,我们等待它们完成(按照您的方式),然后按照预期安排结果。


推荐阅读