1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python open ascii codec cant_Python3.6 报错问题:'ascii' codec can't encode character

python open ascii codec cant_Python3.6 报错问题:'ascii' codec can't encode character

时间:2021-07-17 14:53:17

相关推荐

python open ascii codec cant_Python3.6 报错问题:'ascii' codec can't encode character

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

1 #!D:/Program Files/Python36

2

3 importurllib.request4

5 classWeatherHandle:6

7 #初始化字符串

8 url = u"http://api./telematics/v3/weather?output=json&"

9

10 ak = u""

11

12 defgetWeather(self, city):13

14 url_like = self.url + 'location=' + city + '&ak=' +self.ak15

16 response =urllib.request.urlopen(url_like).read()17

18 print(response)

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

1 importsys2 print(sys.getdefaultencoding());

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

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

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

1 #!D:/Program Files/Python36

2

3 importurllib.request4

5 classWeatherHandle:6

7 #初始化字符串

8 url = u"http://api./telematics/v3/weather?output=json&"

9

10 ak = u""

11

12 defgetWeather(self, city):13

14 url_like = self.url + 'location=' + urllib.parse.quote(city) + '&ak=' +self.ak15

16 response =urllib.request.urlopen(url_like).read()17

18 print(response)

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

1 #!D:/Program Files/Python36

2

3 importurllib.request4

5 classWeatherHandle:6

7 #初始化字符串

8 url = u"http://api./telematics/v3/weather?output=json&"

9

10 ak = u""

11

12 defgetWeather(self, city, time):13

14 url_like = self.url + 'location=' + city + '&ak=' +self.ak15

16 response =urllib.request.urlopen(url_like).read()17

18 print(response.decode('utf-8'))

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。