zoukankan      html  css  js  c++  java
  • Python3.6 报错问题:'ascii' codec can't encode character

    当我使用 urllib.request.urlopen 访问 http://api.map.baidu.com/telematics/v3/weather?output=json&location=北京&ak=**** 的时候,程序报错了:

     1 #!D:/Program Files/Python36
     2 
     3 import urllib.request
     4 
     5 class WeatherHandle:
     6     
     7     # 初始化字符串
     8     url = u"http://api.map.baidu.com/telematics/v3/weather?output=json&"
     9 
    10     ak = u""
    11 
    12     def getWeather(self, city):
    13 
    14         url_like = self.url + 'location=' + city + '&ak=' + self.ak
    15 
    16         response = urllib.request.urlopen(url_like).read()
    17 
    18         print(response)

    错误的信息提示主要集中在最下面的三行中,从这三行可以看出是编码问题,我经过了一番百度之后,一开始有人叫我使用 sys.getdefaultencoding() 这个方法来设置成 utf-8 编码格式,但我输出打印了一下,我当然的编码格式就是 utf-8:

    1 import sys
    2 print(sys.getdefaultencoding());

    如此可见,Python3.6 默认的编码就是 utf-8,Python2.X 的解决方法是不是这个,我没有进行尝试。

    后来我又找了一篇文章,文章中说:URL 链接不能存在中文字符,否则 ASCII 解析不了中文字符,由这句语句错误可以得出 self._output(request.encode('ascii'))。

    所以解决办法就是将URL链接中的中文字符进行转码,就可以正常读取了:

     1 #!D:/Program Files/Python36
     2 
     3 import urllib.request
     4 
     5 class WeatherHandle:
     6     
     7     # 初始化字符串
     8     url = u"http://api.map.baidu.com/telematics/v3/weather?output=json&"
     9 
    10     ak = u""
    11 
    12     def getWeather(self, city):
    13 
    14         url_like = self.url + 'location=' + urllib.parse.quote(city) + '&ak=' + self.ak
    15 
    16         response = urllib.request.urlopen(url_like).read()
    17 
    18         print(response)

    这样就不会出现上述的错误了。但是我们现在显示的是乱码,我们只需要在输出的时候,使用 decode("utf-8") 将结果集转化为 utf-8 编码,就能正常显示了:

     1 #!D:/Program Files/Python36
     2 
     3 import urllib.request
     4 
     5 class WeatherHandle:
     6     
     7     # 初始化字符串
     8     url = u"http://api.map.baidu.com/telematics/v3/weather?output=json&"
     9 
    10     ak = u""
    11 
    12     def getWeather(self, city, time):
    13 
    14         url_like = self.url + 'location=' + city + '&ak=' + self.ak
    15 
    16         response = urllib.request.urlopen(url_like).read()
    17 
    18         print(response.decode('utf-8'))

    以上就是我解决问题的方法了,由于小编是刚学 Python 不久,所以技术水平还很菜,如果上面有什么会误导大家的,希望大家能指正一下,小编会立刻修改。

  • 相关阅读:
    JQuery增加,替换,删除属性应用
    JQuery选择器
    响应式布局
    在 macOS 下备份/还原/重置 LaunchPad 布局
    使用 C# 和 OpenGL (SharpGL) 实现的一个简易画图版
    深入理解计算机系统 (CS:APP)
    深入理解计算机系统 (CS:APP) Lab2
    深入理解计算机系统 (CS:APP) 缓冲区漏洞实验 – Buffer Lab 解析
    ECNU 计算机系统 (CSAPP) 教材习题作业答案集
    计算机网络 Computer Networks​ 期末复习总提纲
  • 原文地址:https://www.cnblogs.com/kafeixiaoluo/p/8472084.html
Copyright © 2011-2022 走看看