Requests库使用

来源:互联网 发布:网络跳线架 编辑:程序博客网 时间:2024/06/06 02:08

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

GET

import requestsurl = '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 requestsurl1 = '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=Trueprint res2.raw.read(50)print type(res2.text)#返回解码成unicode的内容print res2.urlprint res2.history#追踪重定向print res2.cookiesprint res2.cookies['example_cookie_name']print res2.headersprint res2.headers['Content-Type']print res2.headers.get('content-type')print res2.json#讲返回内容编码为jsonprint res2.encoding#返回内容编码print res2.status_code#返回http状态码print res2.raise_for_status()#返回错误状态码

此处模拟登录方法借用了res1.cookies,实现不同请求之间的状态保持,可以借用session对象简要完成
#-*- coding:utf-8 -*-import requestss = 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 requestsproxies = {  'http': 'http://10.10.1.10:3128',  'https': 'http://10.10.1.10:1080',}requests.get('http://example.org', proxies=proxies)




0 0
原创粉丝点击