python - 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 中处理并发的东西,也是第一次使用堆栈溢出来提问。
解决方案
也许这会帮助你理解线程。
每个线程将花费自己的处理时间,并在完成后返回。所以你不会看到像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)
.
在这种类型的设置中,我们等待它们完成(按照您的方式),然后按照预期安排结果。
推荐阅读
- java - 为什么上下文不会从 (Reactor) Mono 传播到 (RxJava) Single?
- c# - 如何使用运算符'??' 关于浮动类型
- tensorflow - Tensorflow Hub 与 Tensorflow 官方模型有什么区别?
- laravel - 登录后 Laravel 基本身份验证重定向到 HTTPS 路由
- gitlab - Gitlab-ci 中的服务以错误“主机类型网络不能与链接一起使用”开始
- css - 不同路线的404页面不起作用
- react-native - 在 React 中显示 json 嵌套对象
- python - 如何使用 Google Analytics API 显示特定的页面浏览量?
- node.js - 如何从 nodejs 中的打字稿文件中读取对象?
- python - 在 R 脚本中嵌入(通过网状)python 代码时无法完成 Cron 作业