requests模块--python发送http请求
requests模块
在Python内置模块(urllib、urllib2、httplib)的基础上进行了高度的封装,从而使得Pythoner更好的进行http请求,使用Requests可以轻而易举的完成浏览器可有的任何操作。Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库。
requests使用
一、GET请求
向 https://github.com/timeline.json 发送一个GET请求,将请求和响应相关均封装在 ret 对象中。
1、无参数实例
|
1
2
3
4
5
6
|
2、有参数实例
|
1
2
3
4
5
6
7
|
import requests payload = {'key1': 'value1', 'key2': 'value2'} print ret.urlprint ret.text |
二、POST请求
向https://api.github.com/some/endpoint发送一个POST请求,将请求和相应相关的内容封装在 ret 对象中。
1、基本POST实例
|
1
2
3
4
5
6
|
import requests payload = {'key1': 'value1', 'key2': 'value2'} print ret.text |
2、发送请求头和数据实例
|
1
2
3
4
5
6
7
8
9
10
11
|
import requestsimport json payload = {'some': 'data'}headers = {'content-type': 'application/json'} ret = requests.post(url, data=json.dumps(payload), headers=headers) print ret.textprint ret.cookies |
3、其他请求
|
1
2
3
4
5
6
7
8
9
10
|
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) |
更多参数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send data
before giving up, as a float, or a :ref:`(connect timeout, read
timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``.
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
:return: :class:`Response <Response>` object
:rtype: requests.Response
Usage::
>>> import requests
<Response [200]>
"""
# By using the 'with' statement we are sure the session is closed, thus we
# avoid leaving sockets open which can trigger a ResourceWarning in some
# cases, and look like a memory leak in others.
with sessions.Session() as session:
return session.request(method=method, url=url, **kwargs)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
def request(method, url, **kwargs): """Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json data to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': ('filename', fileobj)}``) for multipart encoding upload. :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) <timeouts>` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``. :param stream: (optional) if ``False``, the response content will be immediately downloaded. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :return: :class:`Response <Response>` object :rtype: requests.Response Usage:: >>> import requests <Response [200]> """ # By using the 'with' statement we are sure the session is closed, thus we # avoid leaving sockets open which can trigger a ResourceWarning in some # cases, and look like a memory leak in others. with sessions.Session() as session: return session.request(method=method, url=url, **kwargs) |
更多详细资料
更多requests模块相关的文档见:http://cn.python-requests.org/zh_CN/latest/
requests模块--python发送http请求的更多相关文章
- python发送网络请求
1.使用urllib模块(使用不方便,建议使用第二种) get请求: res = urlopen(url) from urllib.request import urlopen url = 'http ...
- requests:用于发送http请求,专为人类设计
介绍 requests模块是一个专门用来发送http请求的模块 如何发送请求 import requests """ 使用requests模块发送请求非常简单 首先请求有 ...
- python发送post请求上传文件,无法解析上传的文件
前言 近日,在做接口测试时遇到一个奇葩的问题. 使用post请求直接通过接口上传文件,无法识别文件. 遇到的问题 以下是抓包得到的信息: 以上请求是通过Postman直接发送请求的. 在这里可以看到消 ...
- Python发送http请求时遇到问题总结
1.报错信息为“ERROR 'str' object has no attribute 'endwith'”,排查发现endswith方法名写错了,少了s,写成了 'endwith' if inter ...
- Python 学习之urllib模块---用于发送网络请求,获取数据
1.urllib urllib是Python标准库的一部分,包含urllib.request,urllib.error,urllib.parse,urlli.robotparser四个子模块. (1) ...
- Python 学习之urllib模块---用于发送网络请求,获取数据(5)
查询城市天气最后一节 需要导入上一节的结果city10.py #!/usr/bin/python# -*- coding: UTF-8 -*-import urllib.requestfrom ci ...
- Python 学习之urllib模块---用于发送网络请求,获取数据(4)
承接将查询城市编码的结果保存到文件中,以字典的形式保存,目的是为了在查询某个城市的天气的时候,能够通过输入的城市名称,找到对应的城市编码.所以此结果字典的数据结构,就是city={城市名称:城市编码} ...
- Python 学习之urllib模块---用于发送网络请求,获取数据(3)
上节内容,是得到了省/直辖市编码,如web='http://m.weather.com.cn/data5/city01',我们需要继续获取此接口的数据,于是进行下面的操作 for i in b ...
- Python 学习之urllib模块---用于发送网络请求,获取数据(2)
接着上一次的内容. 先说明一下关于split()方法:它通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串(把一个字符串分割成很多字符串组成的list列表) 语法: ...
随机推荐
- React Native也正式发布了
var React = require('react-native'); var { TabBarIOS, NavigatorIOS } = React; var App = React.create ...
- 用c#开发微信 系列汇总
网上开发微信开发的教程很多,但c#相对较少.这里列出了我所有c#开发微信的文章,方便自己随时查阅. 一.基础知识 用c#开发微信(1)服务号的服务器配置和企业号的回调模式 - url接入 (源码下 ...
- STC12C5A60S2笔记1(管脚定义)
STC12C5A60S2管脚定义 管脚1:标准IO口P1.0.ADC0 模数转换通道0.CLKOUT2 波特率发生器的时钟输出 管脚2:标准IO口P1.1.ADC1 模数转换通道1 管脚3:标准IO口 ...
- 团队项目——站立会议DAY6
团队项目--站立会议 DAY6 团队成员介绍(5人):张靖颜.何玥.钟灵毓秀.赵莹.王梓萱 今日(2016/5/13),站立会议已进行了一周时间,大家将这一周所遇到的问题和 ...
- [.net 面向对象编程基础] (12) 面向对象三大特性——继承
[.net 面向对象编程基础] (12) 面向对象三大特性——继承 上节我们说了面向对象的三大特性之一的封装,解决了将对同一对象所能操作的所有信息放在一起,实现统一对外调用,实现了同一对象的复用,降低 ...
- 用curl向指定地址POST一个JSON格式的数据
昨天的一个任务,用POST 方式向一个指定的URL推送数据.以前都用的数组来完成这个工作. 现在要求用json格式.感觉应该是一样的.开写. <?php $post_url = "ht ...
- AWS系列之三 使用EBS
Amazon Elastic Block Store(EBS)可作为EC2实例的持久性数据块级存储.其具有高可用性和持久性的特点,可用性高达99.999%.给现有的EC2实例扩展新的存储块只需要几分钟 ...
- 12小时包你学会基于ReactMix框架的ReactNativeApp开发(二)基于Css+HTML写第一个app页面
上一篇文章,大家对于ReactMix(https://github.com/xueduany/react-mix)框架有了一个基本认识,知道我们是一个语法糖,帮助大家基于一套代码,所有平台都能跑.那么 ...
- 深入分析Java Web技术内幕(修订版)
阿里巴巴集团技术丛书 深入分析Java Web技术内幕(修订版)(阿里巴巴集团技术丛书.技术大牛范禹.玉伯.毕玄联合力荐!大型互联网公司开发应用实践!) 许令波 著 ISBN 978-7-121- ...
- vue.js学习之入门实例
之前一直看过vue.js官网api,但是很少实践,这里抽出时间谢了个入门级的demo,记录下一些知识点,防止后续踩坑,牵扯到的的知识点:vue.vue-cli.vue-router.webpack等. ...