如何关闭对流式广播流url的请求



我正在用请求爬取几个页面,发现了一个无线电流的url。我基本上只是想跳过它或做一些超时,但请求没有结束:

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

我以为设置stream=False就可以了,不是吗?我还尝试过将头标头设置为['Connection']='close',但这也不起作用。在这两种情况下,请求都不会关闭。

谢谢!

实际上,代码的行为与预期的一样,但参数可能并不意味着您所期望的。timeout是服务器开始发送响应所需的时间限制,但您正在访问的服务器开始响应所需时间不长。。。但它发送了无限的响应。另一方面,当设置为true(默认值)时,stream将等待,直到下载了全部内容;同样,内容永远不会结束,所以调用永远不会返回(可能会吃掉你的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特有的,请选择更适合您的。

最新更新