我试图从网页检索字符集(这会一直改变)。目前我使用 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,因为这是未知的编码。
Thanks
我最终使用的最终代码:
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
import re
def get_encoding(soup):
if soup and soup.meta:
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:
raise ValueError('unable to find encoding')
else:
raise ValueError('unable to find encoding')
return encod
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)