相比较Python标准库中的urllib模块来说,Requests模块的API使用起来更加友好,其继承了urllib的所有特性,并且支持HTTP连接保持和连接池,支持cookie保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的URL和POST数据自动编码。
开源地址:https://github.com/kennethreitz/requests。用到的同学去给个star吧。
基本的GET请求
import requests
#最基本的GET请求可以直接使用get方法
response = requests.get("http://www.baidu.com/")
#添加headers和查询参数
kw = {'wd':'詹姆斯'}
headers = {
'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
}
url = "http://www.baidu.com/"
response = requests.get(url,params=kw,headers=headers)
#查看相应内容,response.text返回的是Unicode格式的数据
print(response.text)
#response.content返回的是字节流的数据
print(response.content)
#查看完整URL地址
print(resp