【发布时间】:2013-08-21 13:39:12
【问题描述】:
我正在尝试从网页中检索字符集(这将一直更改)。目前我使用 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% 准确,因此想尝试从页面本身获取编码。
标签: python character-encoding beautifulsoup webpage