【发布时间】:2022-01-27 13:39:30
【问题描述】:
我有以下功能来抓取网页。
def parse(link: str, list_of_samples: list, index: int) -> None:
# Some code to scrape the webpage (link is given)
# The code will generate a list of strings, say sample
list_of_samples[index] = sample
我有另一个脚本,它为列表中存在的所有 URL 调用上述脚本
def call_that_guy(URLs: list) -> list:
samples = [None for i in range(len(URLs))]
for i in range(len(URLs)):
parse(URLs[i], samples, i)
return samples
调用上述函数的其他函数
def caller() -> None:
URLs = [url_1, url_2, url_3, ..., url_n]
# n will not exceed 12
samples = call_thay_guy(URLs)
print(samples)
# Prints the list of samples, but is taking too much time
我注意到的一件事是解析函数需要大约 10 秒来解析单个网页(我使用的是 Selenium)。因此,解析列表中存在的所有 URL 大约需要 2 分钟。我想加快速度,可能使用多线程。
我尝试执行以下操作。
import threading
def call_that_guy(URLs: list) -> list:
threads = [None for i in range(len(URLs))]
samples = [None for i in range(len(URLs))]
for i in range(len(URLs)):
threads[i] = threading.Thread(target = parse, args = (URLs[i], samples, i))
threads[i].start()
return samples
但是,当我打印返回值时,它的所有内容都是None。
我想要实现什么:
我想异步抓取 URL 列表并填充示例列表。填充列表后,我还有一些其他语句要执行(它们应该仅在填充样本后执行,否则它们会导致异常)。我想更快地抓取 URL 列表(允许异步),而不是一个接一个地抓取它们。
(我可以用图片更清楚地解释一些事情)
【问题讨论】:
标签: python-3.x multithreading selenium