2011-08-13 6 views
3

Beautiful Soup과 Python 2.6.5를 사용하여 스칸디나비아 문자로 웹 사이트에서 텍스트와 HTML을 추출하려고합니다. 실행될 때아름다운 스프와 문자 인코딩

html = open('page.html', 'r').read() 
soup = BeautifulSoup(html) 

descriptions = soup.findAll(attrs={'class' : 'description' }) 

for i in descriptions: 
    description_html = i.a.__str__() 
    description_text = i.a.text.__str__() 
    description_html = description_html.replace("/subdir/", "http://www.domain.com/subdir/") 
    print description_html 

그러나, 프로그램은 다음과 같은 오류 메시지와 함께 실패 : 그 어떤 도움 있다면

Traceback (most recent call last): 
    File "test01.py", line 40, in <module> 
     description_text = i.a.text.__str__() 
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 19:   ordinal not in range(128) 

입력 페이지, ISO-8859-1로 인코딩 된 것으로 보인다. BeautifulSoup(html, fromEncoding="latin-1")으로 올바른 소스 인코딩을 설정해 보았지만 도움이되지 않았습니다.

2011 년입니다. 그리고 나는 사소한 문자 인코딩 문제로 씨름하고 있습니다.이 모든 것에 대한 정말 간단한 해결책이 있다고 생각합니다.

답변

3
i.a.__str__('latin-1') 

또는

i.a.text.encode('latin-1') 

작동합니다.

당신은 그것이 latin-1일까요? 인코딩을 올바르게 감지해야합니다.

또한 인코딩을 지정하지 않아도되는 경우 str(i.a)을 사용하지 않는 이유는 무엇입니까?

편집 : 자동으로 인코딩을 감지하려면 install chardet이 필요합니다.

+0

'i.a.text.encode ('latin-1')'매우 효과적입니다. 감사합니다! –

0

독일어 스프레드 시트를 출력하는 데 실패한 Beautiful Soup과 동일한 문제가 발생했습니다.

 title = str(link.contents[0].string) 

이 준 'UnicodeEncodeError :' 는 불행하게도 내 문제가 해결되지 않은 경우에도 유래에 대한 답변의 무수한있다 아스키 코덱 문자 U를 인코딩 할 수없는 '를 \ xe4'위치 32 :하지 서수 범위 (128)

많은 답변에는 올바른 해결 방법에 대한 유용한 지침이 있습니다. 로 레나 Regebro는 UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3 2: ordinal not in range(128)에서 말한다 :

When you do str(u'\u2013') you are trying to convert the Unicode string to a 8-bit string. To do this you need to use an encoding, a mapping between Unicode data to 8-bit data. What str() does is that is uses the system default encoding, which under Python 2 is ASCII. ASCII contains only the 127 first code points of Unicode, that is \u0000 to \u007F1. The result is that you get the above error, the ASCII codec just doesn't know what \u2013 is (it's a long dash, btw).

나를 위해, 그것은 문자열 형식으로 아름다운 수프 개체를 변환하는 STR()를 사용하지 않는 단순한 사건이었다. 콘솔의 기본 출력을 무시한 것은 별 차이가 없었습니다.

  ### title = str(link.contents[0].string) 
      ### should be 
      title = link.contents[0].encode('utf-8')