我正在构建一个网络爬虫API,大部分的爬取工作都是使用AsyncIO协程完成的,例如:
async def parse_event(self):
do scraping
# call the func
asyncio.run(b.parse_event())
这很完美地运作,但由于我需要同时从多个网站抓取数据,所以一开始我使用了concurrent.futures.ThreadPoolExecutor
进行多线程爬虫。
但是自从我实现了协程逻辑后,我现在不能直接在我的线程中使用asyncio.run
方法。
之前(没有协程):
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
w1_future = executor.submit(self.w1.parse_event)
w2_future = executor.submit(self.w2.parse_event)
w3_future = executor.submit(self.w3.parse_event)
然后,我期望看到以下类似的内容:
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
w1_future = executor.submit(asyncio.run(self.w1.parse_event))
w2_future = executor.submit(asyncio.run(self.w2.parse_event))
w3_future = executor.submit(asyncio.run(self.w3.parse_event))
很不幸,它没有起作用。
executor.submit(asyncio.run, self.w1.parse_event)
。 - MisterMiyagiasyncio.run
是否保证线程安全?由于文档中没有提到,我认为它不是线程安全的,因此不安全。 - freakishasyncio.run
传递给执行程序是不安全的。 - freakish