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

 时间:2026-02-12 00:32:06

1、打开开发工具IDLE,新建‘urlencode.py’文件,并写代码如下:

import urllib.request


city = '上海'
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.request


city = '上海'
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.request


city = '上海'
key = 'yourkey'
dvar = {
    'city':city,
    'key':key
    }
incode = urllib.parse.urlencode(dvar)
url = 'http://apis.juhe.cn/simpleWeather/query?'+incode
s = urllib.request.urlopen(url)
print (s.read())

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

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

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

7、使用quote就只能自行拼接字符串请求了,注意解码响应内容,代码如下:

import urllib.request


city = '上海'
key = 'yourkey'
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安装成功,却不能运行的解决方法
  • 热门搜索
    江泰旅游保险网 广东旅游地图 恩施大峡谷旅游 山东旅游网 夕阳红旅游团 阿拉善旅游 桂林旅游价格 芜湖旅游景点 川藏线旅游 九寨沟旅游注意事项