Python的requests模块

原文链接:http://wyb0.com/posts/2016/python-module-requests/

无参数的get请求

import requests

resp = requests.get('http://www.baidu.com',timeout=1) #设置了超时
print resp.text #一般用来输出纯文本
print resp.content #一般用来输出pdf、图片等
requests_text.png

有参数的get请求

import requests

url = 'http://10.10.10.10:8080/Lab2.0/Login.action'
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
}
payload = {'aaa':'1111','bbb':'2222'}
resp = requests.get(url,params=payload,headers=header)
print resp.url #得到url
print resp.status_code #得到返回的状态码
print resp.headers #得到html头
print resp.cookies #得到cookie
requests_get_params.png

POST请求

import requests
url1 = 'http://10.10.10.10:8080/Lab2.0/Login.action'
url2 = 'http://10.10.10.10:8080/Lab2.0/student.action'
payload = {
    'userid':'1315935xxx',
    'password':'xxxxxxx',
    'quan':'Student',
}
header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
}
resp = requests.post(url1,data=payload,headers=header)
cookie = resp.cookies #保存cookie
resp = requests.get(url2,cookies=cookie) #要加上cookie
print resp.text
requests_post.png

使用Session

import requests
url = 'http://10.10.10.10:8080/Lab2.0/Login.action'
proxie = {
    'http':'http://127.0.0.1:8080'
}
payload = {
    'userid':'1315935xxx',
    'password':'xxxxxxx',
    'quan':'Student',
}
s = requests.Session() #此后请求时不用再声明cookie
resp = s.post(url,data=payload,proxies=proxie)
# 此时再次请求就不用使用cookie了
resp = s.get('http://10.10.10.10:8080/Lab2.0/student.action')
print resp.text
requests_proxies.png
requests_post.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,969评论 19 139
  • 慕课网requests库学习笔记: 第一章:准备 安装客户端: 安装服务端: 启动服务端: 第二章:HTTP协议原...
    码农小杨阅读 489评论 0 0
  • http协议有http0.9,http1.0,http1.1和http2三个版本,但是现在浏览器使用的是htt...
    一现_阅读 1,897评论 0 3
  • 被蒙在鼓里的我,看着她古灵精怪的小眼神心想:行吧,那就不猜了,反正明天就什么都知道了。其实心里一直嘀咕着这熊...
    华少阳光阅读 741评论 0 0
  • 有的时候觉得你们一定是我的朋友,有的时候觉得我们一定不是朋友。 有的时候觉得你是喜欢和我在一起,有的时候...
    choinicc阅读 321评论 0 0