gpt4 book ai didi

python - 如何使用 multiprocessing 遍历一个大的 URL 列表?

转载 作者:太空宇宙 更新时间:2023-11-04 09:49:11 25 4
gpt4 key购买 nike

问题:检查超过 1000 个 url 的列表并获取 url 返回码 (status_code)。

我的脚本可以运行,但速度很慢。

我认为必须有更好的 pythonic(更漂亮)方法来执行此操作,我可以在其中生成 10 或 20 个线程来检查 url 并收集响应。(即:

200 -> www.yahoo.com
404 -> www.badurl.com
...

输入文件:Url10.txt

www.example.com
www.yahoo.com
www.testsite.com

....

import requests

with open("url10.txt") as f:
urls = f.read().splitlines()

print(urls)
for url in urls:
url = 'http://'+url #Add http:// to each url (there has to be a better way to do this)
try:
resp = requests.get(url, timeout=1)
print(len(resp.content), '->', resp.status_code, '->', resp.url)
except Exception as e:
print("Error", url)

挑战:通过多处理提高速度。


多处理

但它不起作用。我收到以下错误:(注意:我不确定我是否正确实现了这一点)

AttributeError: Can't get attribute 'checkurl' on <module '__main__' (built-in)>

--

import requests
from multiprocessing import Pool

with open("url10.txt") as f:
urls = f.read().splitlines()

def checkurlconnection(url):

for url in urls:
url = 'http://'+url
try:
resp = requests.get(url, timeout=1)
print(len(resp.content), '->', resp.status_code, '->', resp.url)
except Exception as e:
print("Error", url)

if __name__ == "__main__":
p = Pool(processes=4)
result = p.map(checkurlconnection, urls)

最佳答案

在这种情况下,您的任务是 I/O 绑定(bind)而不是处理器绑定(bind) - 网站回复所需的时间比您的 CPU 循环一次脚本(不包括 TCP 请求)所需的时间更长。这意味着您不会通过并行执行此任务获得任何加速(multiprocessing 所做的)。你想要的是多线程。实现这一点的方法是使用很少记录的、可能命名不当的 multiprocessing.dummy:

import requests
from multiprocessing.dummy import Pool as ThreadPool

urls = ['https://www.python.org',
'https://www.python.org/about/']

def get_status(url):
r = requests.get(url)
return r.status_code

if __name__ == "__main__":
pool = ThreadPool(4) # Make the Pool of workers
results = pool.map(get_status, urls) #Open the urls in their own threads
pool.close() #close the pool and wait for the work to finish
pool.join()

See here有关 Python 中多处理与多线程的示例。

关于python - 如何使用 multiprocessing 遍历一个大的 URL 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48551440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com