当我使用 urllib.request.urlopen 访问 http://api.map.baidu.com/telematics/v3/weather?output=json&location=北京&ak=**** 的时候,程序报错了:json
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:api
1 import sys 2 print(sys.getdefaultencoding());
如此可见,Python3.6 默认的编码就是 utf-8,Python2.X 的解决方法是否是这个,我没有进行尝试。编码
后来我又找了一篇文章,文章中说:URL 连接不能存在中文字符,不然 ASCII 解析不了中文字符,由这句语句错误能够得出 self._output(request.encode('ascii'))。url
因此解决办法就是将URL连接中的中文字符进行转码,就能够正常读取了:spa
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 编码,就能正常显示了:3d
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 不久,因此技术水平还很菜,若是上面有什么会误导你们的,但愿你们能指正一下,小编会马上修改。code