Python:从URL获取Shoutcast/网络电台名称

3 投票
1 回答
3266 浏览
提问于 2025-04-16 00:23

我一直在尝试通过网址获取网络电台的名称或标题,用Python来实现,但到现在为止都没有成功。看起来网络电台使用的协议和HTTP不太一样,如果我说错了请纠正我。

比如说这个网址:http://89.238.146.142:7030

它的标题是:“Ibiza Global Radio”。

我该怎么把这个标题存到一个变量里呢?任何帮助都会非常感激 :)

祝好,
frigg

1 个回答

8

从一点点的 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() 的调用,因为我觉得这些头部名称是大小写不敏感的,但大致就是这个意思。

撰写回答