【问题标题】:UnicodeWarning: Unicode equal comparison. How to replace non-standard characters in NavigableString dataype?UnicodeWarning:Unicode 相等比较。如何替换 NavigableString 数据类型中的非标准字符?
【发布时间】:2012-08-20 09:39:09
【问题描述】:

我正在使用 BeautifulSoup 使用 Python 2.7 抓取网站。这是我的代码:

# -*- coding: utf-8 -*-

from BeautifulSoup import BeautifulSoup
import urllib
import json

url = 'http://www.website.com'
file_pointer = urllib.urlopen(url)
html_object = BeautifulSoup(file_pointer)

type_select = html_object('select',{'id':'which'})

for option in type_select:
    value = option('option')
    for type_value in value:
        type =  type_value.contents[0]
        param_1 = type_value['value']
        print 'Type:', type

        url2 = 'http://www/website.com/' + param_1
        file_pointer2 = urllib.urlopen(url2)
        html_object2 = BeautifulSoup(file_pointer2)
        result = json.loads(str(html_object2))

        for json1 in result['DATA']:
            category = json1[0].title()
            param_2 = json1[0]
            print '   Category:', category

            url3 = 'http://www/website.com/' + param_2 + '&which=' + param_1
            file_pointer3 = urllib.urlopen(url3)
            html_object3 = BeautifulSoup(file_pointer3)
            result2 = json.loads(str(html_object3))

            for json2 in result2['DATA']:
                sub_category = json2[0]
                param_3 = sub_category.replace(' ','+').replace('&','%26')
                print '       sub_category:', sub_category

                for i in param_3:
                    if i == 'â':
                        print i
  ...

我需要为第四个 URL 请求替换 'â' 字符以继续我的抓取,但无论我尝试替换什么(u'\u2019'â 等),我都会得到一个 UnicodeEncodeError

我尝试将 param_3 转换为字符串(因为它是 BeautifulSoup Navigable String 数据类型)并替换,但我得到了同样的错误,除了我的 str(param_3) 行。我终于尝试了这个for循环比较并得到了警告:

UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
if i == 'â':

我在这里不知所措。如何翻译此字符并将其替换为param_3 中的其他字符?

感谢任何帮助!提前致谢!

【问题讨论】:

    标签: unicode python-2.7 beautifulsoup urllib scrape


    【解决方案1】:

    BeautifulSoup 返回 Unicode 字符串,因此在对它们进行操作时使用 Unicode 字符串。另请查看urllib.quote_plus。看起来它可以完成您想要的替换。在将其与 quote_plus 一起使用之前,您需要 .encode Unicode 字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-01
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2016-04-14
      • 2022-12-03
      相关资源
      最近更新 更多