搜索
您的当前位置:首页正文

Python Http请求模块(Requests)

来源:筏尚旅游网
1、在Python内置模块(urllib、urllib2、httplib)的基础上进行了高度的封装,从而使得Pythoner更好的进行http请求,使用Requests可以轻而易举的完成浏览器可有的任何操作。Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库。
2、Requests使用案例:
(1)Get请求
向 https://github.com/timeline.json 发送一个GET请求,将请求和响应相关均封装在 ret 对象中。
  • 无参数实例
import requests
  
ret = requests.get('https://github.com/timeline.json')
  
print ret.url
print ret.text
  • 有参数实例
import requests
  
payload = {'key1': 'value1', 'key2': 'value2'}
ret = requests.get("http://httpbin.org/get", params=payload)
  
print ret.url
print ret.text
(2)Post请求
向https://api.github.com/some/endpoint发送一个POST请求,将请求和相应相关的内容封装在 ret 对象中。
  • 基于post实例
import requests
  
payload = {'key1': 'value1', 'key2': 'value2'}
ret = requests.post("http://httpbin.org/post", data=payload)
  
print ret.text

  • 发送请求头和数据实例
import requests
import json
  
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
  
ret = requests.post(url, data=json.dumps(payload), headers=headers)
  
print ret.text
print ret.cookies
  • 其他请求实例
requests.get(url, params=None, **kwargs)
requests.post(url, data=None, json=None, **kwargs)
requests.put(url, data=None, **kwargs)
requests.head(url, **kwargs)
requests.delete(url, **kwargs)
requests.patch(url, data=None, **kwargs)
requests.options(url, **kwargs)
  
# 以上方法均是在此方法的基础上构建
requests.request(method, url, **kwargs)

因篇幅问题不能全部显示,请点此查看更多更全内容

Top