당신이 HTML을 구문 분석하고 original_encoding
attrbute에 액세스 할 수 있습니다 BeautifulSoup로 사용 :
import urllib2
from bs4 import BeautifulSoup
html = urllib2.urlopen('http://www.sohu.com').read()
soup = BeautifulSoup(html)
>>> soup.original_encoding
u'gbk'
을 그리고 이것은 HTML의 <head>
의 <meta>
태그에 선언 된 인코딩과 일치 : 이제
<meta http-equiv="content-type" content="text/html; charset=GBK" />
>>> soup.meta['content']
u'text/html; charset=GBK'
을 수행 할 수 있습니다 HTML을 디코드하십시오 :
decoded_html = html.decode(soup.original_encoding)
하지만, HTML 이후 많지 않은 점은 유니 코드로 이미 사용할 수 있습니다 :
>>> soup.a['title']
u'\u641c\u72d0-\u4e2d\u56fd\u6700\u5927\u7684\u95e8\u6237\u7f51\u7ad9'
>>> print soup.a['title']
搜狐-中国最大的门户网站
>>> soup.a.text
u'\u641c\u72d0'
>>> print soup.a.text
搜狐
이 chardet
모듈을 사용하여 검색을 시도 할 수도 있습니다 (이 있지만 조금 느린) :
>>> import chardet
>>> chardet.detect(html)
{'confidence': 0.99, 'encoding': 'GB2312'}
고마워요! 나는 초보자이다. –
@ ZhangYongsheng : 천만에. – mhawke
글쎄, 나는 또한 문제가있다. 어쩌면, 그것은 당신을 위해 쉽습니다. 내가 압축을 푼 후 [link] (http://www.sina.com.cn)의 html 웹 페이지를 다운로드하려고하는데 UnicodeDecodeError가 있습니다. 'ascii'코덱은 1 바이트 위치 0x8b를 디코딩 할 수 없습니다. 서수는 범위 내에 있지 않습니다 (128). 그래서 그것을 유니 코드로 gb2312 형태로 디코딩하려고 시도합니다. 그렇다면 beautifulsoup를 사용하십시오. 그렇지 않으면 unicodeDecodeError가 발생합니다. –