【问题标题】:How to escape a unicode error when converting a BeautifulSoup object to a string将 BeautifulSoup 对象转换为字符串时如何转义 unicode 错误
【发布时间】:2015-01-23 17:38:27
【问题描述】:

我一直在使用以下代码,试图提取此网页的文本元素。

site= 'http://football.fantasysports.yahoo.com/f1/1785/4/team?&week=4'
print site
response = urllib2.urlopen(site)
html = response.read()

soup = BeautifulSoup(html)
position = soup.find_all('span', class_="Fz-xxs")
for j in range(0,13):
    positionlist = str(position[j].get_text())

print (positionlist)

不幸的是,被放入位置列表字符串的文本本身包含许多无法编码的连字符(即:SEA-RB)。当我尝试按原样运行代码时,我得到以下响应:

Traceback (most recent call last):
  File "/Users/masongardner/Desktop/TestSorter.py", line 20, in <module>
    positionlist = str(position[j].get_text())
UnicodeEncodeError: 'ascii' codec can't encode character u'\ue002' in position 0: ordinal not in range(128)

我知道连字符无法编码,但我不确定如何更改编码,以便在可能的情况下让 unicode 解释连字符,或者忽略连字符并仅对每个字符之前和之后的文本进行编码实例。这个项目纯粹是为了我自己的使用,所以黑客的方法不是问题!

谢谢大家!

【问题讨论】:

  • 您可以使用翻译表,然后编码为 ascii。看看这个related question

标签: python python-2.7 unicode-string


【解决方案1】:

不要尝试转换为 str,只需打印您从 get_text 获得的 unicode 字符串:

site= 'http://football.fantasysports.yahoo.com/f1/1785/4/team?&week=4'

print site
response = urllib2.urlopen(site)
html = response.read()

soup = BeautifulSoup(html)
position = soup.find_all('span', class_="Fz-xxs")
for j in range(0,13):
    positionlist = (position[j].get_text()) # unicode string

    print (positionlist)
Viewing Info for League: The League (ID# 1785)
 # http://chars.suikawiki.org/char/E002




Since '08
Jax - QB

Atl - WR

Ten - WR

您将看到源代码&lt;span class="F-icon Fz-xxs"&gt;&amp;#xe002;&lt;/span&gt;&lt;/a&gt; 中的确切内容

如果您想忽略该字符,请使用 if positionlist != u"\ue002":

你也可以使用unicodedata:

 import unicodedata
 print unicodedata.normalize('NFKD', positionlist).encode('ascii','ignore')

【讨论】:

    【解决方案2】:

    你也可以这样做

     try:
        print(word)
     except Exception: 
        print(str(word.encode("utf-8",'ignore')))
    

    【讨论】:

      【解决方案3】:

      get_text()(顾名思义)已经返回了一个文本——Unicode 字符串。你不应该打电话给str();您可以直接打印 Unicode 文本:

      >>> str(u'\N{SNOWMAN}')                                                                                   
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      UnicodeEncodeError: 'ascii' codec can't encode character u'\u2603' in position 0: ordinal not in range(128)
      >>> print u'\N{SNOWMAN}'
      ☃
      

      如果需要将 Unicode 字符串转换为字节;调用.encode()方法(不要使用str()):

      bytestring = unicode_text.encode(character_encoding)
      

      【讨论】:

        【解决方案4】:

        position[j].get_text() 实际上为您提供了一个“unicode”输出,您无法将其转换为实际上是字节流的“str”,而无需指定要使用的编码。默认情况下,它假定您需要 ASCII,然后当它发现不是 ASCII 的内容时会引发错误。

        如果要打印到控制台,则无需转换为 str。 但是很可能您想发送到某个地方,所以请提及编码,如果您不知道哪个坚持使用 UTF-8,因为大多数应用程序都使用 UTF-8。另外,请检查如何忽略非 ASCII 字符。

        【讨论】:

          猜你喜欢
          • 2016-10-26
          • 1970-01-01
          • 2015-06-09
          • 2010-12-09
          • 1970-01-01
          • 2010-11-02
          相关资源
          最近更新 更多