2014-10-03 44 views
1

我用请求爬几页,遇到了无线电流的网址。我基本上只是想跳过它或做一些超时,但该请求并没有结束:如何关闭对流式广播流url的请求?

u = 'http://streaming.radionomy.com/Cheche-International-Radio' 
print 'started...', u 
r = requests.get(u, timeout=1, stream=False) 

我认为设置流=假会做到这一点,不是吗?我也尝试设置标题头['Connection'] ='close',但这也不起作用。在这两种情况下,请求都不会关闭。

谢谢!

+0

我冲一下关于contextlib的东西https://docs.python.org/2/library/contextlib.html#contextlib.closing – 2014-10-03 07:11:29

回答

2

实际上,代码的行为与预期的一样,但参数并不意味着您期望的。 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,选择什么样的工作适合你更好。