Python高手之路【八】python基础之requests模块
1、Requests模块说明
Requests 是使用 Apache2 Licensed 许可证的 HTTP 库。用 Python 编写,真正的为人类着想。
Python 标准库中的 urllib2 模块提供了你所需要的大多数 HTTP 功能,但是它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。
在Python的世界里,事情不应该这么麻烦。
Requests 使用的是 urllib3,因此继承了它的所有特性。Requests 支持 HTTP 连接保持和连接池,支持使用 cookie 保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码。现代、国际化、人性化。
(以上转自Requests官方文档)
2、Requests模块安装
requests模块下载地址:http://docs.python-requests.org/en/latest/user/install/#install
然后执行安装,解压文件,进入到文件目录,看到setup.py文件,即可!在空白处按住shift键,点右键,选择”在此处打开命令窗口“,然后敲下面的命令
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
Python高手之路【八】python基础之requests模块的更多相关文章
- Python高手之路  ------读书有感
		最近忙中偷闲把前些年买的<Python高手之路>翻了出来,大致看完了一遍,其中很多内容并不理解,究其原因应该是实践中的经验不足,而这对于现如今的我仍是难以克服的事情,对此也就只能说是看会了 ... 
- 《Python高手之路 第3版》这不是一本常规意义上Python的入门书!!
		<Python高手之路 第3版>|免费下载地址 作者简介 · · · · · · Julien Danjou 具有12年从业经验的自由软件黑客.拥有多个开源社区的不同身份:Debian开 ... 
- python开发之路:python数据类型(老王版)
		python开发之路:python数据类型 你辞职当了某类似微博的社交网站的底层python开发主管,官还算高. 一次老板让你编写一个登陆的程序.咔嚓,编出来了.执行一看,我的妈,报错? 这次你又让媳 ... 
- Python高手之路【七】python基础之模块
		本节大纲 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configparse ... 
- Python菜鸟之路:Python基础-模块
		什么是模块? 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护.为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,分组的规则就是把实现了某个 ... 
- Python菜鸟之路:Python基础(二)
		一.温故而知新 1. 变量命名方式 旧的方式: username = 'xxxx' password = 'oooo' 新的方式: username, password = 'xxxx', 'oooo ... 
- Python高手之路【一】初识python
		Python简介 1:Python的创始人 Python (英国发音:/ˈpaɪθən/ 美国发音:/ˈpaɪθɑːn/), 是一种解释型.面向对象.动态数据类型的高级程序设计语言,由荷兰人Guido ... 
- 我的Python成长之路---第六天---Python基础(18)---2016年2月20日(晴)
		os模块 提供对操作系统进行调用的接口 >>> import os >>> os.getcwd() # 获取当前工作目录,类似linux的pwd命令 '/data/ ... 
- python学习之路-1 python简介及安装方法
		python简介 一种面向对象.解释型计算机程序设计语言,由Guido van Rossum于1989年发明,第一个公开发行版发行于1991年. 目前最新版本为3.5.1,发布于2015年12月07日 ... 
随机推荐
- 复杂领域的Cynefin模型和Stacey模型
			最近好奇“复杂系统”,收集了点资料,本文关于Cynefin模型和Stacey模型.图文转自互联网后稍做修改. Cynefin模型提供一个从因果关系复杂情度来分析当前情况而作决定的框架,提出有五个领域: ... 
- [leetcode] Bitwise AND of Numbers Range
			Bitwise AND of Numbers Range Given a range [m, n] where 0 <= m <= n <= 2147483647, return t ... 
- C语言错误之--初始值(低级错误)
			今天犯了一个低级错误,虽然低级,但是也不能忽视,一个低级错误以后可能小则浪费时间和精力,大则酿成整个app的项目bug. 
- CentOS6.5安装mysql5.1.73
			思路: 1.查看有无安装过mysql rpm -qa|grep mysql 
- Linux写时拷贝技术(copy-on-write)
			COW技术初窥: 在Linux程序中,fork()会产生一个和父进程完全相同的子进程,但子进程在此后多会exec系统调用,出于效率考虑,linux中引入了“写时复制“技术,也就是只有进程空间的各段的内 ... 
- JJ Ying:越来越跨界的界面设计
			2013年6月29号 星期六 小雨 @大众点评 利用非界面设计的专业知识来提升界面设计 向平面设计跨界 向工业设计的跨界 向摄影跨界 向动向的的跨界 向程序跨界 讲师介绍: JJ Ying / ... 
- POI教程之第一讲:创建新工作簿, Sheet 页,创建单元格
			第一讲 Poi 简介 Apache POI 是Apache 软件基金会的开放源码函数库,Poi提供API给java程序对Microsoft Office格式档案读和写的功能. 1.创建新工作簿,并给工 ... 
- 烂泥:centos6.4服务器添加新硬盘
			本文由秀依林枫提供友情赞助,首发于烂泥行天下. 公司FTP服务器的空间又不够了,唉,没有办法只能新加硬盘了.因为以前没有给Linux服务器添加过硬盘,所以只能先在虚拟机中进行模拟. 新加硬盘的操作步骤 ... 
- html点击按钮 弹出 多选择窗口级联下拉复选
			参考代码 代码示例1: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:/ ... 
- 形如(function(){}).call()的js语句
			研究新浪微博的自动登陆流程,其中涉及到它的加密算法脚本,其中有一段如下形式的代码: (function(){...}).call(name) 其中红色的....是函数的内部各种实现,name为一个对象 ... 
