【问题标题】:I just want to download this URL...but it is giving me an error! ...unicode.. (Python)我只想下载这个网址……但它给了我一个错误! ...unicode..(Python)
【发布时间】:2010-12-20 23:38:49
【问题描述】:
theurl = 'http://bit.ly/6IcCtf/'
urlReq = urllib2.Request(theurl)
urlReq.add_header('User-Agent',random.choice(agents))
urlResponse = urllib2.urlopen(urlReq)
htmlSource = urlResponse.read()
if unicode == 1:
    #print urlResponse.headers['content-type']
    #encoding=urlResponse.headers['content-type'].split('charset=')[-1]
    #htmlSource = unicode(htmlSource, encoding)
    htmlSource =  htmlSource.encode('utf8')
return htmlSource

请查看 unicode 部分。我已经尝试了这两个选项...但不起作用。

htmlSource =  htmlSource.encode('utf8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 370747: ordinal not in range(128)

当我尝试更长的编码方法时也是如此......

_mysql_exceptions.Warning: Incorrect string value: '\xE7\xB9\x81\xE9\xAB\x94...' for column 'html' at row 1

【问题讨论】:

    标签: python http unicode urllib2 encode


    【解决方案1】:

    您的 html 数据是来自互联网的字符串已经编码,并带有一些编码。在将其编码为 utf-8 之前,您必须先对其进行解码

    Python 隐性试图对其进行解码(这就是为什么你会得到UnicodeDecodeError 而不是UnicodeEncodeError)。

    您可以通过显式解码您的字节串(使用适当的编码)尝试将其重新编码为utf-8 来解决问题。

    例子:

    utf8encoded = htmlSource.decode('some_encoding').encode('utf-8')
    

    使用页面最初编码的正确编码,而不是'some_encoding'

    必须在解码之前知道字符串使用的是哪种编码。

    【讨论】:

      【解决方案2】:

      不解码? htmlSource = htmlSource.decode('utf8')

      decode 意思是“从 utf8 编码解码 htmlSource”

      encode 表示“将 htmlSource 编码为 utf8 编码”

      由于您是提取现有数据(从网站爬取),您需要对其进行解码,并且当您插入到 mysql 时,您可能需要根据您的 mysql db/table/fields 排序规则编码为 utf8。

      【讨论】:

      • 我想对其进行编码,以便将其插入数据库
      【解决方案3】:

      可能你想解码 Utf8,而不是编码它:

      htmlSource =  htmlSource.decode('utf8')
      

      【讨论】:

        猜你喜欢
        • 2015-07-21
        • 2020-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-16
        • 2022-01-09
        • 2023-03-21
        • 1970-01-01
        相关资源
        最近更新 更多