Requests库使用

HTTP请求大致有GET、POST、PUT、DELETE、HEAD、OPTIONS六种,对应到requests库上的使用方法依次为

GET

import requests
url = 'http://www.baidu.com'
payload = {'key1': 'value1', 'key2': 'value2'}
headers = {}
r = requests.get(url, params=payload, headers=headers)
print r.text
其中payload为GET携带的数据,附在url后面


POST

#-*- coding:utf-8 -*-
import requests
url1 = 'http://www.exanple.com/login'#登陆地址
url2 = "http://www.example.com/main"#需要登陆才能访问的地址
data={"user":"user","password":"pass"}
headers = { "Accept":"text/html,application/xhtml+xml,application/xml;",
            "Accept-Encoding":"gzip",
            "Accept-Language":"zh-CN,zh;q=0.8",
            "Referer":"http://www.example.com/",
            "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
            }
res1 = requests.post(url1, data=data, headers=headers)
res2 = requests.get(url2, cookies=res1.cookies, headers=headers)

print res2.content#获得二进制响应内容
print res2.raw#获得原始响应内容,需要stream=True
print res2.raw.read(50)
print type(res2.text)#返回解码成unicode的内容
print res2.url
print res2.history#追踪重定向
print res2.cookies
print res2.cookies['example_cookie_name']
print res2.headers
print res2.headers['Content-Type']
print res2.headers.get('content-type')
print res2.json#讲返回内容编码为json
print res2.encoding#返回内容编码
print res2.status_code#返回http状态码
print res2.raise_for_status()#返回错误状态码

此处模拟登录方法借用了res1.cookies,实现不同请求之间的状态保持,可以借用session对象简要完成
#-*- coding:utf-8 -*-
import requests
s = requests.Session()
url1 = 'http://www.exanple.com/login'#登陆地址
url2 = "http://www.example.com/main"#需要登陆才能访问的页面地址
data={"user":"user","password":"pass"}
headers = { "Accept":"text/html,application/xhtml+xml,application/xml;",
            "Accept-Encoding":"gzip",
            "Accept-Language":"zh-CN,zh;q=0.8",
            "Referer":"http://www.example.com/",
            "User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36"
            }
res1 = s.post(url1, data=data, headers=headers)
res2 = s.get(url2, headers=headers)
print(res2.content)
其他请求使用方式类似,为
>>> r = requests.put("http://httpbin.org/put")
>>> r = requests.delete("http://httpbin.org/delete")
>>> r = requests.head("http://httpbin.org/get")
>>> r = requests.options("http://httpbin.org/get")
除此之外,requests设置代理的方式为
import requests

proxies = {
  'http': 'http://10.10.1.10:3128',
  'https': 'http://10.10.1.10:1080',
}

requests.get('http://example.org', proxies=proxies)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值