2010-06-24 82 views

回答

7

从一个小curl,它似乎是使用shoutcast协议,所以你正在寻找一个早期开头的行icy-name:

$ curl http://89.238.146.142:7030 | head -5 
    % Total % Received % Xferd Average Speed Time Time  Time Current 
           Dload Upload Total Spent Left Speed 
100 13191 0 13191 0  0 16013  0 --:--:-- --:--:-- --:--:-- 28516ICY 200 OK 
icy-notice1:<BR>This stream requires <a href="http://www.winamp.com/">Winamp</a><BR> 
icy-notice2:SHOUTcast Distributed Network Audio Server/Linux v1.9.8<BR> 
icy-name:Ibiza Global Radio 
icy-genre:Electronic 
100 33463 0 33463 0  0 30954  0 --:--:-- 0:00:01 --:--:-- 46579 
curl: (23) Failed writing body 
$ 

因此:

>>> import urllib2 
>>> f = urllib2.urlopen('http://89.238.146.142:7030') 
>>> for i, line in enumerate(f): 
... if line.startswith('icy-name') or i > 20: break 
... 
>>> if i > 20: print 'failed to find station name' 
... else: print 'station name is', line.replace('icy-name:', '') 
... 
station name is Ibiza Global Radio 

>>> 

您可能需要添加例如一些.lower()调用,因为我相信这些标头名称是不区分大小写的,但这是一般的想法。

+0

感谢您提供了一个很好的解决方案和一个彻底的解释!保存了我的一天:) – frigg 2010-06-25 07:50:48

+0

现在有点老了,但这些只是http标题。您应该将它们作为普通标题访问,而不是通过刮取回复的内容。 f = urllib2.urlopen(someurl)。打印f.headers ['冰 - 名']。 – 2013-12-25 00:53:55

+0

经过多一点挖掘之后,似乎有些发脑袋站点不使用标题,只是将所有内容填充到响应内容中。可悲的是,这可能是处理这些问题的最佳方式。 – 2013-12-25 03:21:51