python 网络请求类库 requests 使用

requests是 为python封装的强大 REST 操作类库

1: 安装,请使用 pip,或是 easy_install 工具

sudo pip install requests

2: 使用 先

import requests

#coding=utf-8
#要加上编码设置,不然编译不通过,这是python2的问题 '''
Created on 2014年4月22日 @author: dev.keke@gmail.com
''' #测试 request库环境,python2.7环境 import requests #GET 请求
r = requests.get('http://httpbin.org/get')
print 'GET:',r.text #POST 请求
r = requests.post('http://httpbin.org/post')
print 'POST',r.text #GET 带参数请求,
pararms = {'key1':'value1','key2':'value2'}
r = requests.get('http://httpbin.org/get',params=pararms)
print 'GET Pararms',r.url,r.text #POST 带参数请求,
parar={'key1':'value1','key2':'value2'}
r = requests.post('http://httpbin.org/post',params = parar)
print 'POST Pararms:',r.url,r.text #改变响应数据的编码
r.encoding = 'ISO-8859-1' #取得响应的二进制数据
r.content #取得json数据,如果数据json处理失败,会抛出异常
r.json() #响应原始数据内容,注意设置 r = requests.get('https://github.com/timeline.json', stream=True) tream = True
r.raw #原数据内容

3:一些更为复杂的操作

定制请求头

>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'} >>> r = requests.post(url, data=json.dumps(payload), headers=headers)

复杂的post请求

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print r.text
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'} >>> r = requests.post(url, data=json.dumps(payload))

上传文件

>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')} >>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'))} >>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "<censored...binary...data>"
},
...
}
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')} >>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "some,data,to,send\\nanother,row,to,send\\n"
},
...
}

响应状态码:

内置状态码:

>>> r.status_code == requests.codes.ok
True

根据状态码抛出异常

>>> bad_r = requests.get('http://httpbin.org/status/404')
>>> bad_r.status_code
404 >>> bad_r.raise_for_status()
Traceback (most recent call last):
File "requests/models.py", line 832, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error

查看响应头

>>> r.headers
{
'status': '200 OK',
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json; charset=utf-8'
}

设置请求超时时间

>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

参考:http://cn.python-requests.org/zh_CN/latest/user/quickstart.html

python 网络请求类库 requests 使用的更多相关文章

  1. Python网络请求urllib和urllib3详解

    Python网络请求urllib和urllib3详解 urllib是Python中请求url连接的官方标准库,在Python2中主要为urllib和urllib2,在Python3中整合成了urlli ...

  2. Python 网络请求模块 urllib 、requests

    Python 给人的印象是抓取网页非常方便,提供这种生产力的,主要依靠的就是 urllib.requests这两个模块. urlib 介绍 urllib.request 提供了一个 urlopen 函 ...

  3. 04.Python网络爬虫之requests模块(1)

    引入 Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用. 警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症.冗余代码症.重新发明轮子症.啃文档 ...

  4. Python网络爬虫之requests模块(1)

    引入 Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用. 警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症.冗余代码症.重新发明轮子症.啃文档 ...

  5. 04,Python网络爬虫之requests模块(1)

    引入 Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用. 警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症.冗余代码症.重新发明轮子症.啃文档 ...

  6. 06.Python网络爬虫之requests模块(2)

    今日内容 session处理cookie proxies参数设置请求代理ip 基于线程池的数据爬取 知识点回顾 xpath的解析流程 bs4的解析流程 常用xpath表达式 常用bs4解析方法 引入 ...

  7. Python网络爬虫之requests模块(2)

    session处理cookie proxies参数设置请求代理ip 基于线程池的数据爬取 xpath的解析流程 bs4的解析流程 常用xpath表达式 常用bs4解析方法 引入 有些时候,我们在使用爬 ...

  8. Python网络爬虫之requests模块

    今日内容 session处理cookie proxies参数设置请求代理ip 基于线程池的数据爬取 知识点回顾 xpath的解析流程 bs4的解析流程 常用xpath表达式 常用bs4解析方法 引入 ...

  9. python网络请求简洁之道--python requests简介

    #requests中文文档:http://cn.python-requests.org/en/latest/#学习出处:http://mp.weixin.qq.com/s?__biz=MjM5NzU0 ...

随机推荐

  1. Opencv学习笔记1:安装opencv和VS2015并进行环境配置

    用了Opencv一段时间了,简单记录一下opencv在vs2015下的配置. 第一部分:OpenCV3.2.0的下载 OpenCV官方下载地址: https://opencv.org/releases ...

  2. bzoj 3944 杜教筛

    题目中要求phi和miu的前缀和,利用杜教筛可以推出公式.我们令为 那么有公式 类比欧拉函数,我们可以推出莫比乌斯函数的和公式为  (公式证明懒得写了,主要核心是利用Dirichlet卷积的性质 ph ...

  3. 【静态主席树】POJ2104-K-th Number

    求区间第k大.裸线段树. 莫队版本:☆ #include<iostream> #include<cstdio> #include<cstring> #include ...

  4. Codechef APRIL14 ANUCBC Cards, bags and coins 背包DP变形

    题目大意 有n个数字,选出一个子集,有q个询问,求子集和模m等于0的方案数%1000000009.(n <= 100000,m <= 100,q <= 30) 假设数据很小,我们完全 ...

  5. python开发_difflib字符串比较

    在python的difflib中 HtmlDiff:比较后以html方法展示 我们比较的是字符串: 'hello world!' 和 'hElLO Wor2d!' 具体代码: from difflib ...

  6. HDU 5641 King's Phone 模拟

    King's Phone 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5641 Description In a military parade, ...

  7. windows2008服务器连接Oracle慢的问题。

    昨天发布程序到2008服务器的IIS,从Sql Server数据库取数没问题,但是从Oracle数据库取数,非常的慢,同样的程序在2003服务器上没问题,本机也没问题.一开始怀疑是这台机器有问题,后来 ...

  8. ES6系列汇总

    汇 总 第一节:什么是ES6?新手该如何理解 第二节:ES6新增了let关键字,干嘛用的? 第三节:ES6中另一个不得不说的关键字const 第四节:教你如何快速让浏览器兼容ES6特性 第五节:一个令 ...

  9. Buck converter uses low-side PWM IC

    The most common switching-power topology is a buck converter, which efficiently transforms high volt ...

  10. java 日期工具类

    import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; imp ...