首页 > 编程语言 > 详细

Python利器一之requests

时间:2018-12-25 10:35:09      阅读:164      评论:0      收藏:0      [点我收藏+]

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的使用。

Python利器一之requests

原文:https://www.cnblogs.com/BenLam/p/10172438.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!