2014-10-03 36 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,選擇什麼樣的工作適合你更好。