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. Tornado(二)

    跨站请求伪造CSRF 开启xsrf(就是叫法不一样和csrf一样),'xsrf_cookies':True settings = { 'template_path':'template', 'stat ...

  2. java switch

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha switch 是 开关:转换 的意思. 支持的数据类型 有 : 字节,字符,短整型,整型 ...

  3. [NC13B]贝伦卡斯泰露/[51Nod1400]序列分解

    [NC13B]贝伦卡斯泰露/[51Nod1400]序列分解 题目大意: 给定\(A_{1\sim n}(n\le40)\),问是否能将\(A\)分解成两个相同的子序列? 思路: 折半搜索.时间复杂度\ ...

  4. php正则给图片提取/替换/添加alt标签的正则代码

    有的时候我们需要对富文本编辑器的内容做一些处理,例如图片的alt标签.百度的富文本编辑器添加的图片就是没有的,那么我们要添加就必须使用正则了,下面一起来看看如何实现吧. $preg = "/ ...

  5. SpringBoot返回结果如果为null或空值不显示处理方法

    第一种方法:自定义消息转换器 @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter{ // /** // * ...

  6. SpringBoot 搭建简单聊天室

    SpringBoot 搭建简单聊天室(queue 点对点) 1.引用 SpringBoot 搭建 WebSocket 链接 https://www.cnblogs.com/yi1036943655/p ...

  7. l1和l2正则化的区别 - 面试错题集

    L0:计算非零个数,用于产生稀疏性,但是在实际研究中很少用,因为L0范数很难优化求解,是一个NP-hard问题,因此更多情况下我们是使用L1范数L1:计算绝对值之和,用以产生稀疏性,因为它是L0范式的 ...

  8. bzoj 1211: [HNOI2004]树的计数 -- purfer序列

    1211: [HNOI2004]树的计数 Time Limit: 10 Sec  Memory Limit: 162 MB Description 一个有n个结点的树,设它的结点分别为v1, v2, ...

  9. Java高级架构师(一)第40节:更多模块的基本功能和配置

  10. 我的jlink破解失败经历

    http://fallenwind.spaces.eepw.com.cn/articles/article/item/59116 标题:我的jlink破解失败经历2009-07-12 01:16:56 ...