當我使用 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 不久,所以技術水平還很菜,如果上面有什么會誤導大家的,希望大家能指正一下,小編會立刻修改。
