requests是Python中一个第三方库,基于 urllib,采用Apache2 Licensed开源协议的 HTTP库。它比urllib更加方便,可以节约我们大量的工作,完全满足HTTP测试需求。
因为是第三方库,所以我们想要使用需要安装:
pip install requests
安装完成后import一下,正常则说明可以开始使用了:
import requests
一行代码就可以获取百度首页的数据:
requests.get('http://www.baidu.com/')
是不是非常的简洁方便,其他请求类型也可以,比如POST:
requests.post('http://www.baidu.com/', data = {'key':'value'})
如果想要在请求中传递参数,也非常简单,当然最简单的还是在url中直接添加:
url = 'https://www.baidu.com/s?wd=requests'
requests.get(url)
但是这种方法一看就很low,我们requests库专门设置了一个params参数用来传递参数:
url = 'https://www.baidu.com/s'
params = {'wd': 'requests'}
requests.get(url, params=params)
如果我们想要伪装自己是浏览器,也很简单。requests库设置了headers参数,供我们来设置请求头文件,比如假装是浏览器:
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'}
requests.get('http://www.baidu.com', headers=headers)
到现在,有没有一种感觉就是昨天都白学了,当然,这还没有完,我们再来看看他的响应内容。
在上面的例子可以知道,我们每次请求之后都会返回一个对象,我们可以从此对象中获取响应内容:
response = requests.get("https://api.github.com/events")
print(response.text)
运行结果如下:
[{"id":"6924608641","type":"PushEvent",...}]
获取二进制响应内容
print(response.content)
运行结果如下:
b'[{"id":"6924656608","type":"CreateEvent",...}]'
获取JSON格式的响应内容,如果解码失败,response.json()将会引发异常
print(response.json())
运行结果如下:
[{"id":"6924608641","type":"PushEvent",...}]
获取响应状态码
print(response.status_code)
运行结果如下:
200
获取响应头
print(response.headers)
运行结果如下:
{
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json'
}
最后,再将昨天结尾的程序用requests库实现一下,最终结果与昨天的一致。
import requests
url = 'http://www.phpxs.com/' # 编程学习网搜索页面
params = {
's': 'Python 教程'
} # 参数信息
headers = {
'User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
} # 头部信息
request = requests.get(url, params=params, headers=header)
reponse = request.content
fh = open("Python 教程.html", "wb") # 将文件写入到当前目录中
fh.write(reponse)
fh.close()
好了,关于requests库的介绍就先讲这么多吧,至于其他没想到的知识点,以后用到的时候再说。学完了requests库的基本用法,是不是觉得超级好用呢?
以上就是本次分享的所有内容,想要了解更多欢迎前往公众号:Python 编程学习圈,每日干货分享