【发布时间】:2017-02-01 23:44:58
【问题描述】:
(前言:我知道,这个问题已经讲了一百遍了,但我还是不明白)
我正在尝试加载一个 html 页面并输出文本,即使我正确获取了网页,BeautifulSoup 以某种方式破坏了不属于前 127 个 ASCII 字符的重音字符的编码:
# -*- coding: utf-8 -*-
import sys
from urllib import urlencode
from urlparse import parse_qsl
import re
import urlparse
import json
import urllib
from bs4 import BeautifulSoup
url = "http://www.rtve.es/alacarta/interno/contenttable.shtml?ctx=29010&locale=es&module=&orderCriteria=DESC&pageSize=15&mode=TEXT&seasonFilter=40015"
html=urllib2.urlopen(url).read()
soup = BeautifulSoup(html)
div = soup.find_all("span", class_="detalle")
capitulo_detalle = div[0].text (doesn't work, capitulo_detalle is type str with utf-8, div[0].tex is type unicode)
div[0].text 的输出应该类似于:
Sátur se dirige al sur en busca de Estuarda y Gabi, pero un compañero de viaje inesperado hará que cambie德伦博。 Los hombres de Juan siguen presos。 El enemigo comienza a realizar ejecuciones。 Águila Roja tiene...
但我得到的结果是:
u'S\xe1tur se dirige al sur en busca de Estuarda y Gabi, pero un compa\xf1ero de viaje inesperado har\xe1 que cambie de rumbo。胡安·西根·普雷索斯 . El enemigo comienza a realizar ejecuciones。 \xc1guila Roja tiene...'
--> 要获得“正确”的字符,我必须进行哪些更改?
我知道它一定是这些问题的重复,但答案似乎在这里不起作用: Python and BeautifulSoup encoding issues How to correctly parse UTF-8 encoded HTML to Unicode strings with BeautifulSoup?
我还阅读了有关 unicode、utf-8、ascii 的典型文档,例如https://docs.python.org/3/howto/unicode.html,显然没有成功……
【问题讨论】:
-
如何运行这段代码?在 Python Shell 或
python script.py中?你如何得到这个文本?您是否使用了print div[0].text或 Python Shell 自动为您打印了这个?您有正确的文本,但 Python Shell 使用print repr( div[0].text )显示对调试有用的文本。所以试试print repr(div[0].text)和print div[0].text你会看到不同的文字。 -
我使用的是 Python 2.7.13,示例可以在 Shell 中运行,也可以作为脚本运行,没关系。是的,“打印”显示正确的输出,但我需要变量中的文本。
-
你已经有了正确的字符。文字
u'S\xe1tur se dirige...'正好代表文字Sátur se dirige...。如果您print()它,您将看到原始字符(假设您的控制台可以打印它们,如果是 Windows 则可能不会)。 -
@bobince:是的,但我使用的是 Python 2.7.13 和 utf-8。如果我将 div[0].text(它是 unicode)分配给一个普通的字符串变量(它是 utf-8),我就会遇到麻烦。
-
仅使用
unicode就没有问题了 - 所以将所有字符串转换为 unicode。这是解决方案。
标签: python unicode utf-8 character-encoding beautifulsoup