我正在使用BeautifulSoup4做一些網頁抓取,並且遇到解碼響應問題。網站返回我的標題,在標題中說:使用BeautifulSoup刮取網站時的字符編碼問題
content-type:text/html; charset = ISO-8859-1
所以通常我用latin1字符集來解碼它。但隨後在解碼之後,有在HTML中的線,即表示:
<元含量= 「text/html的;字符集= UTF-8」 HTTP-當量= 「內容類型」/ >
現在從這一行開始字符串沒有正確解碼。
那麼處理這個問題的正常方法是什麼?我想在傳出的http頭文件中設置accept-encoding行,但找不到執行此操作的方法。另一種選擇是解碼逐行尋找新的字符集,但寧願這樣做只是只接受比較UTF-8
我用Python3,libray http.client
EDIT1: 代碼:
import http.client as cl
from bs4 import BeautifulSoup
conn = cl.HTTPConnection('www.amazon.com')
conn.request("GET", '/A-Man-For-All-Seasons/dp/B003TQ1IW6/ref=sr_1_109?s=instant-video&ie=UTF8&qid=1348337540&sr=1-109')
response = conn.getresponse()
content = response.read()
soup = BeautifulSoup(content)
f = open('am.html', 'w')
f.write(soup.prettify())
#i am actually doing this with httplib2 but result is the same
編輯2: 看起來像在Linux中配置Beautiful Soup 4真的是錯誤的,或者它是一個錯誤。 這是工作,但我不能BS4解析響應:
import httplib2
h = httplib2.Http('.cache')
response, content = h.request(movieLink , headers={'accept-charset': 'latin1'})
content = content.decode('latin-1')
謝謝你,Blckknght。
你的代碼適用於我(在Python 3.2.3和Beautiful Soup 4.1.3的Windows上)。我沒有在輸出文件中弄亂任何東西。 – Blckknght
不只是使用亞馬遜的API的任何理由?哦,歡迎來到SO! – vzwick
默認設置正確的請求標題和編碼可以解決這個問題,http://www.datascraping.co/doc/questions/21/encoding-problem-in-website-scraping – Vicky