2009-03-10 6 views
5

BeautifulSoup를 사용하여 웹 사이트를 긁어 모으고 있습니다. 웹 사이트의 페이지가 내 브라우저에서 잘 렌더링됩니다.BeautifulSoup는 나에게 유니 코드 + HTML 기호를 제공합니다. 이것은 버그 또는 오해입니까?

Oxfam International의 보고서 "Offside! http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271

특히, 작은 따옴표와 큰 따옴표는 잘 보입니다. 이상하게도 FF3에서 소스를 볼 때 ASCII 문자가 아닌 html 심볼을 보았습니다. 내가 긁어 때

은 불행히도, 난 XE2 € œOffside \ 자격이

u'Oxfam 국제 같은 \ XE2 € ™의 보고서 를 얻을!

u'Oxfam International\xe2€™s report entitled \xe2€œOffside! 

페이지의 메타 데이터 'ISO-88959-1'인코딩을 나타냅니다

죄송합니다, 나는이 말은. 저는 유니 코드 -> ascii 및 html -> ascii 타사 기능을 사용하여 다른 인코딩을 시도했으며 MS/iso-8859-1 불일치를 살펴 보았습니다. 그러나 사실은 ™과 작은 따옴표, 그리고 유니 코드 + htmlsymbol 콤보를 올바른 ascii 또는 html 기호로 변환 할 수없는 것 같습니다. 제한된 지식으로 인해 도움을 요청합니다.

나는

다음 문제는 내가 거기 다른 재미 문자가 잘못 디코딩 걱정이다, 아스키 따옴표와 행복 "또는"것입니다.

\xe2€™ 

다음은 제가 본 것의 일부를 재현 한 것입니다.

import twill 
from twill import get_browser 
from twill.commands import go 

from BeautifulSoup import BeautifulSoup as BSoup 

url = 'http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271' 
twill.commands.go(url) 
soup = BSoup(twill.commands.get_browser().get_html()) 
ps = soup.body("p") 
p = ps[52] 

>>> p   
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe2' in position 22: ordinal not in range(128) 

>>> p.string 
u'Oxfam International\xe2€™s report entitled \xe2€œOffside!<elided>\r\n' 

http://groups.google.com/group/comp.lang.python/browse_frm/thread/9b7bb3f621b4b8e4/3b00a890cf3a5e46?q=htmlentitydefs&rnum=3&hl=en#3b00a890cf3a5e46

http://www.fourmilab.ch/webtools/demoroniser/

http://www.crummy.com/software/BeautifulSoup/documentation.html

http://www.cs.tut.fi/~jkorpela/www/windows-chars.html

>>> AsciiDammit.asciiDammit(p.decode()) 
u'<p>Oxfam International\xe2€™s report entitled \xe2€œOffside! 

>>> handle_html_entities(p.decode()) 
u'<p>Oxfam International\xe2\u20ac\u2122s report entitled \xe2\u20ac\u0153Offside! 

>>> unicodedata.normalize('NFKC', p.decode()).encode('ascii','ignore') 
'<p>Oxfam International€™s report entitled €œOffside! 

>>> htmlStripEscapes(p.string) 
u'Oxfam International\xe2TMs report entitled \xe2Offside! 

EDIT :

,536,913 63,210

나는 다른 BS 파서 사용하여 시도했다 :

unicodedata.normalize('NFKC', p.decode()).encode('ascii','ignore') 
'<p>Oxfam InternationalTMs report entitled Offside! 

편집 :

import html5lib 
bsoup_parser = html5lib.HTMLParser(tree=html5lib.treebuilders.getTreeBuilder("beautifulsoup")) 
soup = bsoup_parser.parse(twill.commands.get_browser().get_html()) 
ps = soup.body("p") 
ps[55].decode() 

나에게주는

u'<p>Oxfam International\xe2\u20ac\u2122s report entitled \xe2\u20ac\u0153Offside! 

최상의 경우 디코딩이 같은 결과 나에게주는 것이 2 :

FF 3.0이 설치된 Mac OS X 4를 실행 중입니다.7 방화범

2.5

파이썬 (와우, 처음부터이 문제를 언급하지 않았다 나는 믿을 수 없어)

하나 심각 페이지 인코딩 현명한 :-)

을 엉망

+0

"죄송합니다 나는이 무엇을 의미 하는가 "뜻? 백 스페이스 키가 작동하지 않았습니까? –

+0

@ S.Lott : Mac에 백 스페이스 키가 있습니까? – SilentGhost

+3

@SilentGhost : 각 Mac에 하나씩 있습니다. "나는 이것을 의미한다"는 것은 매우 자극적입니다. 백 스페이스를 사용하지 않는 이유는 무엇입니까? 다른 마크 업에서 동일한 문자를 반복하는 것이 중요한 이유는 무엇입니까? 그것은 "우습"니까? –

답변

8

아무것도 정말 없다 당신의 접근 방식에 전혀 문제가 없습니다. 이 경우

import urllib 
html = urllib.urlopen('http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271').read() 
h = html.decode('iso-8859-1') 
soup = BeautifulSoup(h) 

이 페이지의 메타 태그 인코딩에 대해 거짓말을한다 : 나는 아마 내가 persnickity 해요해서, BeautifulSoup로 전달하기 전에 변환을 수행하는 경향이있다. 페이지는 UTF-8로 실제로 ... 파이어 폭스의 페이지 정보는 실제 인코딩을 보여, 당신은 실제로 서버에 의해 반환 된 응답 헤더에이 캐릭터 세트를 볼 수 있습니다

curl -i http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271 
HTTP/1.1 200 OK 
Connection: close 
Date: Tue, 10 Mar 2009 13:14:29 GMT 
Server: Microsoft-IIS/6.0 
X-Powered-By: ASP.NET 
Set-Cookie: COMPANYID=271;path=/ 
Content-Language: en-US 
Content-Type: text/html; charset=UTF-8 

사용 디코드를 할 경우 'UTF -8 '이 (나를 위해 적어도입니다 않았거나) 당신을 위해 작동합니다

import urllib 
html = urllib.urlopen('http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271').read() 
h = html.decode('utf-8') 
soup = BeautifulSoup(h) 
ps = soup.body("p") 
p = ps[52] 
print p 
+0

유익하고 부드러운 답변을 주셔서 대단히 감사합니다. 그것은 정말로 나에게도 효과가있다. –

4

그것은 실제로 UTF-8 CP1252로 misencoded 것 :

>>> print u'Oxfam International\xe2€™s report entitled \xe2€œOffside!'.encode('cp1252').decode('utf8') 
Oxfam International’s report entitled “Offside!