2014-07-08 35 views
1

我試圖從網頁獲取HTML輸出。從urllib中分解HTML輸出

data = response.read() 

給了我這樣的事情:

b'\x1f\x8b\x08\x00\x00\x00\x00\... 

如何可以將這些字符轉換成類似:

"<html><body>.." 

+0

我的意思是HTML代碼< html>< body>等 – user1641071

回答

3

您正在處理一個gzipped響應。您可以通過檢查Content-Encoding響應頭,或者寫一個字節序列的開始到文件驗證這一點,並與file程序來檢查它的類型,如果你使用的是類Unix平臺:

>>> data = '\x1f\x8b\x08\x00\x00\x00\x00' 
>>> f = open('data.bin', 'w') 
>>> f.write(data) 
>>> f.close() 
$ file data.bin 
data.bin: gzip compressed data, last modified: Thu Jun 16 09:32:16 1994 

你可以decode it yourself,但我建議爲requests模塊開溝urllib其中automatically decompresses it

import requests 
response = requests.get(url) 
print response.content 
+0

我認爲它應該是'open('data.bin','wb')',因此它接受二進制數據。或者我錯過了什麼? – hayavuk

+1

@bvukelic在Windows上是這樣的,我總是會忘記那些奇怪的「功能」。它對任何其他平臺都沒有任何影響。而且由於Windows上並不存在['file'](http://linux.die.net/man/1/file)實用程序(就我所知),所以在這種情況下並沒有什麼區別。 –

+0

這很有趣,我不知道那個'功能'。我認爲它在所有平臺上都是一樣的,因爲它在文檔中是隱含的。我從來沒有想過在Linux上沒有'b'的情況下嘗試它。 https://docs.python.org/3.3/tutorial/inputoutput.html#reading-and-writing-files – hayavuk