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 不久,所以技术水平还很菜,如果上面有什么会误导大家的,希望大家能指正一下,小编会立刻修改。

posted @ 2018-02-26 10:57  咖啡屋小罗  阅读(6567)  评论(0编辑  收藏  举报