2014-10-30 88 views
0

我正在处理一个python脚本,它在包含.mp3文件的URL列表上进行迭代;目标是通过请求库,通过头部请求从每个网址提取内容长度。 但是,我注意到头部要求显着减慢剧本;隔离所涉及的一段代码,我,得到1.5分钟(200个网址/请求)执行的时间:http头请求减慢脚本(python请求)

import requests 
import time 

print("start\n\n") 

t1 = time.time() 

for n in range(200): 
    response = requests.head("url.mp3") 
    print(response,"\n") 

t2 = time.time() 

print("\n\nend\n\n") 
print("time: ",t2-t1,"s") 
+0

那么,有什么问题吗? – 2014-10-30 18:19:38

+0

问题是执行所需的时间。我正在开发一个已经存在的应用程序,它具有几乎相同的工作方式(我可以阅读它的源代码,并且我正在吸取灵感),但是要做同样的事情需要几秒钟的时间。 – 5haffl 2014-10-30 19:13:10

+0

您可能想要使用某种形式的并行(多线程/多处理)来同时发出多个网络请求,或者在非阻塞IO上使用表单(例如使用gevent或类似的东西)。 – 2014-10-30 22:44:09

回答

0

你一个很好的解决方案可能是grequests

import grequests 

requests = (grequests.get('http://127.0.0.1/%i.mp3' % i) for u in range(200)) 

for code grequests.map(rs): 
    print 'Status code %i' % code.status_code 
+1

非常感谢。 – 5haffl 2015-07-13 19:40:03