urllib使用详解

一、urllib使用说明

1、字典转查询字符串

urllib.parse.urlencode(query)
将query字典转换为url路径中的查询字符串

2、查询字符串转字典

urllib.parse.parse_qs(qs)
将qs查询字符串格式数据转换为python的字典

3、发送请求

urllib.request.urlopen(url, data=None)
发送http请求,如果dataNone,发送GET请求,如果data不为None,发送POST请求
返回response响应对象,可以通过read()读取响应体数据,需要注意读取出的响应体数据为bytes类型

二、实例

1、字典转查询字符串

import urllib
a={1:1}
b=urllib.parse.urlencode(a)
b='1=1'

2、查询字符串转字典

import urllib
a='1=1'
b=urllib.parse.parse_qs(a)
b={'1':['1']}

3、发送请求

from urllib.request import urlopen
response=urlopen('https://www.baidu.com/')
response.read().decode()

猜你喜欢

转载自blog.csdn.net/Uzizi/article/details/81323360