Python requests模块实例用法


Posted in Python onFebruary 11, 2019

1、Requests模块说明

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

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

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

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

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': '2'}
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)

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 相关文章推荐
基于Django filter中用contains和icontains的区别(详解)
Dec 12 Python
使用python实现BLAST
Feb 12 Python
遗传算法python版
Mar 19 Python
windows环境下tensorflow安装过程详解
Mar 30 Python
判断python字典中key是否存在的两种方法
Aug 10 Python
Python split() 函数拆分字符串将字符串转化为列的方法
Jul 16 Python
Pyorch之numpy与torch之间相互转换方式
Dec 31 Python
python十进制转二进制的详解
Feb 07 Python
TensorFlow tf.nn.softmax_cross_entropy_with_logits的用法
Apr 19 Python
Python pip install如何修改默认下载路径
Apr 29 Python
用Python自动清理系统垃圾的实现
Jan 18 Python
教你用Python爬取英雄联盟皮肤原画
Jun 13 Python
说说如何遍历Python列表的方法示例
Feb 11 #Python
python按照多个条件排序的方法
Feb 08 #Python
python 使用pandas计算累积求和的方法
Feb 08 #Python
对Python中的条件判断、循环以及循环的终止方法详解
Feb 08 #Python
解决Pandas的DataFrame输出截断和省略的问题
Feb 08 #Python
对Python之gzip文件读写的方法详解
Feb 08 #Python
Python第三方库h5py_读取mat文件并显示值的方法
Feb 08 #Python
You might like
PHP编程网上资源导航
2006/10/09 PHP
发挥语言的威力--融合PHP与ASP
2006/10/09 PHP
php在window iis的莫名问题的测试方法
2013/05/14 PHP
Destoon模板制作简明教程
2014/06/20 PHP
php实现根据IP地址获取其所在省市的方法
2015/04/30 PHP
浅谈php的TS和NTS的区别
2019/03/13 PHP
php用wangeditor3实现图片上传功能
2019/08/22 PHP
javascript Zifa FormValid 0.1表单验证 代码打包下载
2007/06/08 Javascript
js下用层来实现select的title提示属性
2010/02/23 Javascript
autoPlay 基于jquery的图片自动播放效果
2011/12/07 Javascript
javascript中的=等号个数问题两个跟三个有什么区别
2013/10/23 Javascript
用Jquery.load载入页面实现局部刷新
2014/01/22 Javascript
JavaScript学习笔记(三):JavaScript也有入口Main函数
2015/09/12 Javascript
jQuery实现的placeholder效果完整实例
2016/08/02 Javascript
JS输出空格的简单实现方法
2016/09/08 Javascript
JavaScript 是什么意思
2016/09/22 Javascript
jQuery中ajax错误调试分析
2016/12/01 Javascript
JavaScript调试之console.log调试的一个小技巧分享
2017/08/07 Javascript
jQuery实现用户信息表格的添加和删除功能
2017/09/12 jQuery
在vue项目中引入highcharts图表的方法(详解)
2018/03/05 Javascript
vue使用ajax获取后台数据进行显示的示例
2018/08/09 Javascript
JS使用iView的Dropdown实现一个右键菜单
2019/05/06 Javascript
Vue.js组件实现选项卡以及切换特效
2019/07/24 Javascript
python版本的读写锁操作方法
2016/04/25 Python
Python实现判断字符串中包含某个字符的判断函数示例
2018/01/08 Python
pandas中遍历dataframe的每一个元素的实现
2019/10/23 Python
keras 自定义loss损失函数,sample在loss上的加权和metric详解
2020/05/23 Python
Tensorflow之MNIST CNN实现并保存、加载模型
2020/06/17 Python
HTML+CSS3模拟心的跳动实例代码
2017/09/05 HTML / CSS
优质有机椰子产品:Dr. Goerg
2019/09/24 全球购物
会计试用期自我评价
2015/03/10 职场文书
副总经理岗位职责范本
2015/04/08 职场文书
你会写请假条吗?
2019/06/26 职场文书
粗暴解决CUDA out of memory的问题
2021/05/22 Python
十大最强妖精系宝可梦,哲尔尼亚斯实力最强,第五被称为大力士
2022/03/18 日漫
Mysql 一主多从的部署
2022/05/20 MySQL