1、Requests模块说明

Requests 是使用 Apache2 Licensed 许可证的 HTTP 库。用 Python 编写,真正的为人类着想。

Python 标准库中的 urllib2 模块提供了你所需要的大多数 HTTP 功能,但是它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。

在Python的世界里,事情不应该这么麻烦。

Requests 使用的是 urllib3,因此继承了它的所有特性。Requests 支持 HTTP 连接保持和连接池,支持使用 cookie 保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码。现代、国际化、人性化。

(以上转自Requests官方文档)

2、Requests模块安装

点此下载

然后执行安装

$ python setup.py install

个人推荐使用pip安装

pip install requests

也可以使用easy_install安装

easy_install requests

尝试在IDE中import requests,如果没有报错,那么安装成功。

3、Requests模块简单入门

#HTTP请求类型
#get类型
r = requests.get('https://github.com/timeline.json')
#post类型
r = requests.post("http://m.ctrip.com/post")
#put类型
r = requests.put("http://m.ctrip.com/put")
#delete类型
r = requests.delete("http://m.ctrip.com/delete")
#head类型
r = requests.head("http://m.ctrip.com/head")
#options类型
r = requests.options("http://m.ctrip.com/get") #获取响应内容
print r.content #以字节的方式去显示,中文显示为字符
print r.text #以文本的方式去显示 #URL传递参数
payload = {'keyword': '日本', 'salecityid': ''}
r = requests.get("http://m.ctrip.com/webapp/tourvisa/visa_list", params=payload)
print r.url #示例为http://m.ctrip.com/webapp/tourvisa/visa_list?salecityid=2&keyword=日本 #获取/修改网页编码
r = requests.get('https://github.com/timeline.json')
print r.encoding
r.encoding = 'utf-8' #json处理
r = requests.get('https://github.com/timeline.json')
print r.json() #需要先import json #定制请求头
url = 'http://m.ctrip.com'
headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'}
r = requests.post(url, headers=headers)
print r.request.headers #复杂post请求
url = 'http://m.ctrip.com'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload)) #如果传递的payload是string而不是dict,需要先调用dumps方法格式化一下 #post多部分编码文件
url = 'http://m.ctrip.com'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files) #响应状态码
r = requests.get('http://m.ctrip.com')
print r.status_code #响应头
r = requests.get('http://m.ctrip.com')
print r.headers
print r.headers['Content-Type']
print r.headers.get('content-type') #访问响应头部分内容的两种方式 #Cookies
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies['example_cookie_name'] #读取cookies url = 'http://m.ctrip.com/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies) #发送cookies #设置超时时间
r = requests.get('http://m.ctrip.com', timeout=0.001) #设置访问代理
proxies = {
"http": "http://10.10.10.10:8888",
"https": "http://10.10.10.100:4444",
}
r = requests.get('http://m.ctrip.com', proxies=proxies)

4、Requests示例

json请求

 #!/user/bin/env python
#coding=utf-8
import requests
import json class url_request():
def __init__(self):
""" init """ if __name__=='__main__':
headers = {'Content-Type' : 'application/json'}
payload = {'CountryName':'中国',
'ProvinceName':'陕西省',
'L1CityName':'汉中',
'L2CityName':'城固',
'TownName':'',
'Longitude':'107.33393',
'Latitude':'33.157131',
'Language':'CN'
}
r = requests.post("http://www.xxxxxx.com/CityLocation/json/LBSLocateCity",headers=headers,data=payload)
#r.encoding = 'utf-8'
data=r.json()
if r.status_code!=200:
print "LBSLocateCity API Error " + str(r.status_code)
print data['CityEntities'][0]['CityID'] #打印返回json中的某个key的value
print data['ResponseStatus']['Ack']
print json.dumps(data,indent=4,sort_keys=True,ensure_ascii=False) #树形打印json,ensure_ascii必须设为False否则中文会显示为unicode

xml请求

#!/user/bin/env python
#coding=utf-8
import requests class url_request():
def __init__(self):
""" init """ if __name__=='__main__': headers = {'Content-type': 'text/xml'}
XML = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><Request xmlns="http://tempuri.org/"><jme><JobClassFullName>WeChatJSTicket.JobWS.Job.JobRefreshTicket,WeChatJSTicket.JobWS</JobClassFullName><Action>RUN</Action><Param>1</Param><HostIP>127.0.0.1</HostIP><JobInfo>1</JobInfo><NeedParallel>false</NeedParallel></jme></Request></soap:Body></soap:Envelope>'
url = 'http://jobws.push.mobile.xxxxxxxx.com/RefreshWeiXInTokenJob/RefreshService.asmx'
r = requests.post(url,headers=headers,data=XML)
#r.encoding = 'utf-8'
data = r.text
print data

5、参考文档

http://cn.python-requests.org/en/latest/

http://docs.python-requests.org/en/latest/user/quickstart.html

Python requests模块学习笔记的更多相关文章

  1. python requests库学习笔记(上)

    尊重博客园原创精神,请勿转载! requests库官方使用手册地址:http://www.python-requests.org/en/master/:中文使用手册地址:http://cn.pytho ...

  2. python requests库学习笔记(下)

    1.请求异常处理 请求异常类型: 请求超时处理(timeout): 实现代码: import requestsfrom requests import exceptions        #引入exc ...

  3. Python Requests 库学习笔记

    概览 实例引入 import requests response = requests.get('https://www.baidu.com/') print(type(response)) prin ...

  4. Python shutil 模块学习笔记

    学于https://automatetheboringstuff.com shutil 名字来源于 shell utilities,有学习或了解过Linux的人应该都对 shell 不陌生,可以借此来 ...

  5. Python keyword 模块 -- 学习笔记

    keyword 的帮助文档 >>> import keyword >>> help(keyword) Help on module keyword: NAME ke ...

  6. Python urllib2 模块学习笔记

    2015.3.6  urllib2的使用方法大致如下 # 定制Handler处理函数 opener = urllib2.build_opener(ProxyHandler, HTTPHandler) ...

  7. Requests:Python HTTP Module学习笔记(一)(转)

    Requests:Python HTTP Module学习笔记(一) 在学习用python写爬虫的时候用到了Requests这个Http网络库,这个库简单好用并且功能强大,完全可以代替python的标 ...

  8. Python 日期时间处理模块学习笔记

    来自:标点符的<Python 日期时间处理模块学习笔记> Python的时间处理模块在日常的使用中用的不是非常的多,但是使用的时候基本上都是要查资料,还是有些麻烦的,梳理下,便于以后方便的 ...

  9. python网络爬虫学习笔记

    python网络爬虫学习笔记 By 钟桓 9月 4 2014 更新日期:9月 4 2014 文章文件夹 1. 介绍: 2. 从简单语句中開始: 3. 传送数据给server 4. HTTP头-描写叙述 ...

随机推荐

  1. iOS学习24之UIControl及其子类

    1. UIControl初识 1> 概述 UIControl是有控制功能的视图( 如UIButton.UISlider.UISegmentedControl等)的父类 只要跟控制有关的控件都是继 ...

  2. [R]R语言里的异常处理与错误控制

    之前一直只是在写小程序脚本工具,几乎不会对异常和错误进行控制和处理. 随着脚本结构和逻辑更复杂,脚本输出结果的准确性验证困难,同时已发布脚本的维护也变得困难.所以也开始考虑引入异常处理和测试工具的事情 ...

  3. 【转】vim格式化C代码

    转自:http://blog.chinaunix.net/uid-24774106-id-3396220.html 在自己的目录下编辑自己的.vimrc, vim ~/.vimrc 添加下面的几行: ...

  4. [Java] 利用LinkedHashMap来实现LRU Cache

    http://www.acmerblog.com/leetcode-lru-cache-lru-5745.html https://oj.leetcode.com/discuss/1188/java- ...

  5. 转:jQuery插件开发精品教程,让你的jQuery提升一个台阶

    要说jQuery 最成功的地方,我认为是它的可扩展性吸引了众多开发者为其开发插件,从而建立起了一个生态系统.这好比大公司们争相做平台一样,得平台者得天下.苹果,微软,谷歌等巨头,都有各自的平台及生态圈 ...

  6. 【HDU】4035 Maze

    http://acm.hdu.edu.cn/showproblem.php?pid=4035 题意:给一棵n个节点的树,每个节点有值k[i]和e[i],分别表示k[i]概率走向1号节点,e[i]概率获 ...

  7. jquery 最简单的动画效果

    <p style="border: 1px solid red"> 我会慢慢变大 </p> <a>dianji</a> <sc ...

  8. Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_GiftAnimationView"

    1> error 详情: Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_GiftAnimationView&quo ...

  9. C#_数据转换 实用方法

    [String转Array]string str = "123asd456asd789";单字符: string[] a0 = str.Split('a');多字符: string ...

  10. Linux下设置svn过滤文件类型

    1)修改客户端. 1.修改客户端 1)编辑文件家目录下自己账户下的.subversion/config文件 vim ~/.subversion/config 2)找到包含[miscellany]的一行 ...