【问题标题】:BeautifulSoup: scraping spanish characters issueBeautifulSoup:抓取西班牙语字符问题
【发布时间】:2016-10-29 06:53:52
【问题描述】:

我正在尝试使用 BeautifulSoup 和 urllib2 从网站获取一些西班牙语文本。我目前得到这个:¡Hola! ¿Cómo estás?。 我已经尝试应用我在相关线程上看到的不同 unicode 函数,但似乎对我的问题没有任何作用:

# import the main window object (mw) from aqt
from aqt import mw
# import the "show info" tool from utils.py
from aqt.utils import showInfo
# import all of the Qt GUI library
from aqt.qt import *

from BeautifulSoup import BeautifulSoup

import urllib2



wiki = "http://spanishdict.com/translate/hola"

page = urllib2.urlopen(wiki)

soup = BeautifulSoup(page)

dictionarydiv = soup.find("div", { "class" : "dictionary-neodict-example" })

dictionaryspans = dictionarydiv.contents

firstspan = dictionaryspans[0]

firstspantext = firstspan.contents

thetext = firstspantext[0]

thetextstring = str(thetext)

【问题讨论】:

  • print thetextstring 看起来不错
  • @FranciscoCouzo 仅适用于 UTF-8 终端。 OP 可能在 Windows 上。

标签: python unicode utf-8 beautifulsoup urllib2


【解决方案1】:

thetext 是 <class 'BeautifulSoup.NavigableString'> 类型。打印它会返回一个 Unicode 字符串,该字符串将在输出终端编码中进行编码:

print thetext

输出(在 Windows 控制台中):

¡Hola! ¿Cómo estás?

这将适用于为支持正在打印的 Unicode 字符的编码配置的任何终端。

如果您的终端配置的编码不支持您尝试打印的 Unicode 字符,您将收到 UnicodeEncodeError。

在该类型上使用str 会返回一个字节字符串...在这种情况下以 UTF-8 编码。如果您在除 UTF-8 配置的终端之外的任何设备上打印,您将得到不正确的显示。

【讨论】:

    猜你喜欢
    • 2017-12-29
    • 1970-01-01
    • 2023-03-18
    • 2017-08-22
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多