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
  • 腾讯视频缓存清晰度怎么设置超清720P
  • 不良人手游藏兵谷门怎么开
  • 嵌入式操作系统的任务调度原理
  • 当输入信号过大时,就没有了放大作用。为什么?
  • python3.7.0安装成功,却不能运行的解决方法
  • 热门搜索
    手抄报设计图案大全 汉字王国手抄报 有关于安全的手抄报 消防安全手抄报模板 生命安全手抄报 手抄报花边图片大全 安全消防手抄报 我爱汉字手抄报图片 绿色家园手抄报资料 冬天手抄报