【问题标题】:urlopen() throwing error in python 3.3python 3.3中的urlopen()抛出错误
【发布时间】:2015-01-06 00:49:49
【问题描述】:
from urllib.request import urlopen

def ShowResponse(param):
    uri = str("mysite.com/?param="+param+"&submit=submit")
    print(urlopen(uri).read())

file = open("myfile.txt","r")
if file.mode == "r":
    filelines = file.readlines()
    for line in filelines:
        line = line.strip()
        ShowResponse(line)

这是我的 python 代码,但是当我运行它时会导致错误 "UnicodeEncodeError: 'ascii' codec can't encode characters in position 47-49: ordinal not in range(128)" 我不知道如何解决这个问题。我是python新手

【问题讨论】:

    标签: python-3.x unicode ascii urlopen


    【解决方案1】:

    我将假设堆栈跟踪显示第 4 行 (uri = str(...) 正在引发给定错误,并且myfile.txt 包含 UTF-8 字符。

    错误是因为您试图将 Unicode 对象(从假定的 UTF-8 解码)转换为 ASCII 字符串对象。 ASCII 根本不能代表你的字符。

    URI(包括查询字符串)必须将非 ASCII 字符编码为百分比编码的 UTF-8 字节。示例:

    € (EURO SIGN) 以 UTF-8 编码为:

    0xE2 0x82 0xAC

    百分比编码,它是:

    %E2%82%AC

    因此,您的代码需要将您的参数重新编码为 UTF-8,然后对其进行百分比编码:

    from urllib.request import urlopen, quote
    
    
    def ShowResponse(param):
        param_utf8 = param.encode("utf-8")
        param_perc_encoded = quote(param_utf8)
    
        # or uri = str("mysite.com/?param="+param_perc_encoded+"&submit=submit")
        uri = str("mysite.com/?param={0}&submit=submit".format(param_perc_encoded) )
        print(urlopen(uri).read())
    

    您还会看到我稍微更改了您的 uri = 定义以使用 String.format() (https://docs.python.org/2/library/string.html#format-string-syntax),我发现创建复杂字符串比使用 + 进行字符串连接更容易。在此示例中,{0} 被替换为 .format() 的第一个参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多