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 相关文章推荐
python聊天程序实例代码分享
Nov 18 Python
python判断图片宽度和高度后删除图片的方法
May 22 Python
Python中的sort()方法使用基础教程
Jan 08 Python
python中pandas.DataFrame对行与列求和及添加新行与列示例
Mar 12 Python
详解TensorFlow在windows上安装与简单示例
Mar 05 Python
python判断字符串或者集合是否为空的实例
Jan 23 Python
Python3.8中使用f-strings调试
May 22 Python
window7下的python2.7版本和python3.5版本的opencv-python安装过程
Oct 24 Python
python用tkinter实现一个gui的翻译工具
Oct 26 Python
Python制作简单的剪刀石头布游戏
Dec 10 Python
Python 实现二叉查找树的示例代码
Dec 21 Python
pycharm 的Structure界面设置操作
Feb 05 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+MySQL的聊天室设计
2006/10/09 PHP
PHP中for循环语句的几种变型
2007/03/16 PHP
WordPress导航菜单的滚动和淡入淡出效果的实现要点
2015/12/14 PHP
Laravel SQL语句记录方式(推荐)
2016/05/26 PHP
javascript 类方法定义还是有点区别
2009/04/15 Javascript
JavaScript setTimeout和setInterval的使用方法 说明
2010/03/25 Javascript
js实现双向链表互联网机顶盒实战应用实现
2011/10/28 Javascript
js数组Array sort方法使用深入分析
2013/02/21 Javascript
深入探讨javascript中的数据类型
2015/03/04 Javascript
JavaScript计算两个日期时间段内日期的方法
2015/03/16 Javascript
JS判断iframe是否加载完成的方法
2016/08/03 Javascript
浅谈Node.js:理解stream
2016/12/08 Javascript
Angular的模块化(代码分享)
2016/12/26 Javascript
JavaScript中this的用法及this在不同应用场景的作用解析
2017/04/13 Javascript
前端页面文件拖拽上传模块js代码示例
2017/05/19 Javascript
使用Nodejs连接mongodb数据库的实现代码
2017/08/21 NodeJs
微信小程序自定义带价格显示日历效果
2018/12/29 Javascript
node.js如何操作MySQL数据库
2020/10/29 Javascript
如何在vue 中使用柱状图 并自修改配置
2021/01/21 Vue.js
python对象及面向对象技术详解
2016/07/19 Python
pandas取出重复数据的方法
2019/07/04 Python
将python包发布到PyPI和制作whl文件方式
2019/12/25 Python
Python函数默认参数常见问题及解决方案
2020/03/26 Python
Python实现捕获异常发生的文件和具体行数
2020/04/25 Python
keras 自定义loss损失函数,sample在loss上的加权和metric详解
2020/05/23 Python
Python3爬虫关于代理池的维护详解
2020/07/30 Python
python 基于opencv实现图像增强
2020/12/23 Python
Python 图片处理库exifread详解
2021/02/25 Python
Interhome丹麦:在线预订度假屋和公寓
2019/07/18 全球购物
高中数学教师求职信
2013/10/30 职场文书
《童年的发现》教学反思
2014/02/14 职场文书
房地产促销活动方案
2014/03/01 职场文书
气象学专业个人求职信
2014/04/22 职场文书
师范大学生求职信
2014/06/13 职场文书
银行会计主管岗位职责
2014/10/01 职场文书
布达拉宫的导游词
2015/02/02 职场文书