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 相关文章推荐
zbar解码二维码和条形码示例
Feb 07 Python
Python实现简单多线程任务队列
Feb 27 Python
深入理解Python中的*重复运算符
Oct 28 Python
Python排序搜索基本算法之希尔排序实例分析
Dec 09 Python
Python八大常见排序算法定义、实现及时间消耗效率分析
Apr 27 Python
python 随机打乱 图片和对应的标签方法
Dec 14 Python
python 实现矩阵上下/左右翻转,转置的示例
Jan 23 Python
python并发编程多进程 模拟抢票实现过程
Aug 20 Python
python使用opencv实现马赛克效果示例
Sep 28 Python
python中删除某个元素的方法解析
Nov 05 Python
Pytorch evaluation每次运行结果不同的解决
Jan 02 Python
Python3列表List入门知识附实例
Feb 09 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中用加号与用array_merge合并数组的区别深入分析
2013/06/03 PHP
php多种形式发送邮件(mail qmail邮件系统 phpmailer类)
2014/01/22 PHP
实现PHP+Mysql无限分类的方法汇总
2015/03/02 PHP
PHP 8新特性简介
2020/08/18 PHP
利用XMLHTTP传递参数在另一页面执行并刷新本页
2006/10/26 Javascript
jQuery 方法大全方便学习参考
2010/02/25 Javascript
jquery Mobile入门—多页面切换示例学习
2013/01/08 Javascript
Jquery的Tabs内容轮换效果实现代码,几行搞定
2014/02/12 Javascript
使用jquery.qrcode生成彩色二维码实例
2014/08/08 Javascript
JavaScript通过select动态更换图片的方法
2015/03/23 Javascript
JavaScript动态修改背景颜色的方法
2015/04/16 Javascript
javascript实现选中复选框后相关输入框变灰不可用的方法
2015/08/11 Javascript
js判断浏览器是否支持严格模式的方法
2016/10/04 Javascript
最全正则表达式总结:验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等
2017/08/16 Javascript
JavaScript中.min.js和.js文件的区别讲解
2019/02/13 Javascript
从理论角度讨论JavaScript闭包
2019/04/03 Javascript
vue router动态路由设置参数可选问题
2019/08/21 Javascript
vue 实现通过vuex 存储值 在不同界面使用
2019/11/11 Javascript
解决iview table组件里的 固定列 表格不自适应的问题
2020/11/13 Javascript
[01:20]辉夜杯背景故事宣传片《辉夜传说》
2015/12/25 DOTA
[05:31]干嘛呢兄弟!DOTA2 TI9语音轮盘部分出处
2019/05/14 DOTA
[01:38]女王驾到——至宝魔廷新尊技能&特效展示
2020/06/16 DOTA
python解决Fedora解压zip时中文乱码的方法
2016/09/18 Python
Python 正则表达式入门(中级篇)
2016/12/07 Python
Python编程之Re模块下的函数介绍
2017/10/28 Python
python爬取内容存入Excel实例
2019/02/20 Python
详解Django将秒转换为xx天xx时xx分
2019/09/27 Python
Python 列表的清空方式
2020/01/13 Python
在TensorFlow中屏蔽warning的方式
2020/02/04 Python
python GUI编程(Tkinter) 创建子窗口及在窗口上用图片绘图实例
2020/03/04 Python
英语专业毕业生自我鉴定
2013/11/09 职场文书
专题组织生活会方案
2014/06/15 职场文书
法人委托书
2014/07/31 职场文书
国庆65周年演讲稿:回首往昔,展望未来
2014/09/21 职场文书
党风廉政建设调研报告
2015/01/01 职场文书
2015年大学社团工作总结
2015/04/09 职场文书