实际上,代码的行为与预期的一样,但参数并不意味着您期望的。 timeout
是服务器开始发送响应需要多长时间的时间限制,但您正在访问的服务器不需要很长时间就可以开始响应......但它会发送无限响应。另一方面,当设置为true
(这是默认设置)时,等待整个内容被下载;再次,内容不会结束,所以调用永远不会返回(并且可能会吃掉你的RAM)。
我认为您需要的是使用stream=False
发出请求,查看HTTP标头的响应,并在内容不是您要查找的内容时放弃请求。你可以看看,例如,在Content-Type
;如果你只在text/html
回应有兴趣下面的代码将工作:
u = 'http://streaming.radionomy.com/Cheche-International-Radio'
print 'started...', u
r = requests.get(u, stream=True)
content_type = r.headers['Content-Type']
if content_type.startswith('text/html'):
content = r.content
# process the content
else:
print 'discarded ', u
当然,你可以选择过滤器与其他一些标准的要求。为了您的例子中,标题是:
{
'Expires': 'Mon, 26 Jul 1997 05:00:00 GMT',
'icy-br': '128, 128',
'Pragma': 'no-cache',
'icy-name': 'ChecheInternationalRadio',
'ice-audio-info': 'bitrate=128;samplerate=44100;channels=2',
'Cache-Control': 'no-cache',
'icy-genre': 'medellin',
'Content-Type': 'audio/mpeg',
'icy-description': 'Esta es una Emisora suena solo Exitos Una selecta programacion musical con los mejores artistas y canciones de todos los tiempos. Transmitiendo desde medellin Colombia.',
'icy-pub': '1',
'Accept-Ranges': 'none',
'icy-url': 'http://cheche-international-radio.playtheradio.com/',
'Server': 'Icecast 2.3.3-kh8'
}
其中有些是标准和一些特定于Icecast,选择什么样的工作适合你更好。
我冲一下关于contextlib的东西https://docs.python.org/2/library/contextlib.html#contextlib.closing – 2014-10-03 07:11:29