手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

Python3的urllib模块基本使用urlencode和quote

时间:2024-10-12 02:10:16

1、打开开发工具IDLE,新建‘urlencode.py’文件,并写代码如下:import urllib.requestcity = '上海'key = 'yourkey'dvar = { 'city':city, 'key':key }incode = urllib.parse.urlencode(dvar)print (incode)print (urllib.parse.quote(dvar))这里用的是某和的天气接口,key仅做演示

Python3的urllib模块基本使用urlencode和quote

2、F5运行代码打印信息如下图,urlencode把字典类型数据中文转为utf8编码以‘%’开头key1=vlau1e&key2=value2格式,而quote只能用于string类型

Python3的urllib模块基本使用urlencode和quote

3、测试quote函数改写代码如下;import urllib.requestcity = '上海'key = 'yourkey'dvar = { 'city':city, 'key':key }incode = urllib.parse.urlencode(dvar)print (incode)print (urllib.parse.quote(city))

Python3的urllib模块基本使用urlencode和quote

4、F5运行代码打印信息如下图,可以发现实现在处理中文字符的编码后结果是一样的,还有一个函数quote_plus这个函数能将特殊字符‘/’也进行编码,具体使用时候需要测试编码结果,不可能都记住使用范围

Python3的urllib模块基本使用urlencode和quote

5、测试发送请求,修改代码如下;import urllib.requestcity = &#补朱锚卦39;上海刻八圄俏9;key = 'yourkey'dvar = { 'city':city, 'key':key }incode = urllib.parse.urlencode(dvar)url = 'http://apis.juhe.cn/simpleWeather/query?'+incodes = urllib.request.urlopen(url)print (s.read())

Python3的urllib模块基本使用urlencode和quote

6、F5运行代码,打印内容如下图

Python3的urllib模块基本使用urlencode和quote

7、使用quote就只能自行拼接字符串请求了,注意解码响应内容,代码如下:import urllib.requestcity = '上海'key = 'yourkey&#泌驾台佐39;dvar = { 'city':city, 'key':key }incode = urllib.parse.urlencode(dvar)url = 'http://apis.juhe.cn/simpleWeather/query?'+'city='+urllib.parse.quote(city)+'&key='yourkey's = urllib.request.urlopen(url)print (s.read().decode('utf8'))

Python3的urllib模块基本使用urlencode和quote

8、F5运行代码,正确打印出了结果

Python3的urllib模块基本使用urlencode和quote
© 手抄报圈