python之requests库使用
requests库虽然Python的标准库中 urllib模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests宣传是 “HTTP for Humans”,说明使用更简洁方便。 安装和文档地址:利用 pip install requests
中文文档:http://docs.python-requests.org/zh_CN/latest/index.html 发送GET请求:1. 最简单的发送 response = requests.get("http://www.baidu.com/")
2. 添加headers和查询参数: import requests
kw = {'wd':中国'}
headers = {User-Agent": Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
# params 接收一个字典或者字符串的查询参数,字典类型自动转换为url编码,不需要urlencode()
response = requests.http://www.baidu.com/s",params = kw,headers = headers)
# 查看响应内容,response.text 返回的是Unicode格式的数据
print(response.text)
# 查看响应内容,response.content返回的字节流数据
print(response.content)
# 查看完整URL地址
print(response.url)
# 查看响应头部字符编码
print(response.encoding)
# 查看响应码
print(response.status_code)
发送POST请求:1. 最基本的POST请求可以使用 response = requests.post(2. 传入data数据: |