我試圖從網頁檢索字符集(這將改變所有的時間)。在這一刻我使用beautifulSoup解析頁面,然後從頭中提取字符集。這是工作的罰款,直到我遇到了一個網站,有.....試圖從網頁獲取編碼Python和BeautifulSoup
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
我的代碼到現在爲止並與其他頁面的工作是:
def get_encoding(soup):
encod = soup.meta.get('charset')
if encod == None:
encod = soup.meta.get('content-type')
if encod == None:
encod = soup.meta.get('content')
return encod
有沒有人有一個良好的有關如何添加到此代碼以從上面的示例檢索字符集的想法。將它標記並嘗試以這種方式檢索字符集是一個想法?你將如何去做,而不必改變整個功能? 現在上面的代碼正在返回「text/html; charset = utf-8」,這是導致LookupError,因爲這是一個未知的編碼。
感謝
,我結束了使用的最終代碼:
def get_encoding(soup):
encod = soup.meta.get('charset')
if encod == None:
encod = soup.meta.get('content-type')
if encod == None:
content = soup.meta.get('content')
match = re.search('charset=(.*)', content)
if match:
encod = match.group(1)
else:
dic_of_possible_encodings = chardet.detect(unicode(soup))
encod = dic_of_possible_encodings['encoding']
return encod
我用chardet的,但我想是100%準確,所以想嘗試抓住從編碼頁面本身。 – Craicerjack