Python利器一之requests

Python利器一之requests

一.教程涉及开发语言、脚本、框架、数据库等内容

  • Python + requests
    通过 pip 安装:
pip install requests

通过 easy_install 安装:

easy_install requests

通过以上两种方法均可以完成安装。

二.requests常用请求方式

requests库提供了http所有的基本请求方式,下边是官方例子,使用起来也比较简单,直接请求方式原理请参考协议

req = requests.get("http://httpbin.org/post")
req = requests.post("http://httpbin.org/post")
req = requests.put("http://httpbin.org/put")
req = requests.delete("http://httpbin.org/delete")
req = requests.head("http://httpbin.org/get")
req = requests.options("http://httpbin.org/get")

三.实战示例

  • requests使用小栗子
import requests
req = requests.get('http://www.cnblogs.com')
print(type(req))
print(req.status_code)
print(req.encoding)
print(req.text)
print(req.cookies)

以上代码我们请求了博客园网址,然后打印出了返回结果的类型,状态码,编码方式,Cookies等内容。

返回结果:
<class 'requests.models.Response'>
200
utf-8
<RequestsCookieJar[]>
[Finished in 0.6s]

四.实现请求

  • 模拟登录请求
import requests
data = {"admin":1}
req = requests.post("http://127.0.0.1/login", data=data)
print(req.text)

通过运行返回:

"欢迎admin登录":"0", "token":"xxxxxxxxxx"
  • 通过上边返回的token实现get请求
import requests
headers={"token":"xxxxxxxxxx"}
req = requests.get("http://127.0.0.1/userinfo", headers=headers)
print(req.text)

通过运行返回:

{"user":"admin","msg":"测试"}

通过以上教程实验,相信你已掌握requests的使用。

作者:GI-JOE
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/BenLam/p/10172438.html