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

2025-09-28 06:06:20

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

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢