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使用arp欺骗伪造网关的方法
Apr 24 Python
python互斥锁、加锁、同步机制、异步通信知识总结
Feb 11 Python
浅谈配置OpenCV3 + Python3的简易方法(macOS)
Apr 02 Python
python提取图像的名字*.jpg到txt文本的方法
May 10 Python
python smtplib模块自动收发邮件功能(一)
May 22 Python
python 搜索大文件的实例代码
Jul 08 Python
django搭建项目配置环境和创建表过程详解
Jul 22 Python
django rest framework 实现用户登录认证详解
Jul 29 Python
基于python二叉树的构造和打印例子
Aug 09 Python
Python迷宫生成和迷宫破解算法实例
Dec 24 Python
Python 给下载文件显示进度条和下载时间的实现
Apr 02 Python
使用已经得到的keras模型识别自己手写的数字方式
Jun 29 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输出数组中重名的元素的几种处理方法
2012/09/05 PHP
PHP之uniqid()函数用法
2014/11/03 PHP
基于PHP实现通过照片获取ip地址
2016/04/26 PHP
JavaScript Accessor实现说明
2010/12/06 Javascript
jquery中ajax调用json数据的使用说明
2011/03/17 Javascript
背景图跟随鼠标移动的Mootools插件实现代码
2011/12/12 Javascript
JQuery给元素绑定click事件多次执行的解决方法
2014/05/29 Javascript
JavaScript实现对下拉列表值进行排序的方法
2015/07/15 Javascript
javascript闭包概念简单解析(推荐)
2016/06/03 Javascript
将html页面保存成图片,图片写入pdf的实现方法(推荐)
2016/09/17 Javascript
JS控制页面跳转时未请求要跳转的地址怎么回事
2016/10/14 Javascript
js图片上传的封装代码
2017/08/01 Javascript
使用vue-aplayer插件时出现的问题的解决
2018/03/02 Javascript
vue+elementUi图片上传组件使用详解
2019/08/20 Javascript
JS addEventListener()和attachEvent()方法实现注册事件
2021/01/11 Javascript
[57:28]2018DOTA2亚洲邀请赛 4.6 淘汰赛 TNC vs Liquid 第一场
2018/04/10 DOTA
wxPython中文教程入门实例
2014/06/09 Python
在Mac OS系统上安装Python的Pillow库的教程
2015/11/20 Python
Django学习笔记之ORM基础教程
2018/03/27 Python
Python之lambda匿名函数及map和filter的用法
2019/03/05 Python
python批量处理文件或文件夹
2020/07/28 Python
Python字符串中添加、插入特定字符的方法
2019/09/10 Python
python安装virtualenv虚拟环境步骤图文详解
2019/09/18 Python
详解使用Python下载文件的几种方法
2019/10/13 Python
Pytorch 使用CNN图像分类的实现
2020/06/16 Python
python 线程的五个状态
2020/09/22 Python
Python爬虫教程之利用正则表达式匹配网页内容
2020/12/08 Python
python中zip()函数遍历多个列表方法
2021/02/18 Python
一款纯css3实现的颜色渐变按钮的代码教程
2014/11/12 HTML / CSS
html5 Canvas画图教程(8)—canvas里画曲线之bezierCurveTo方法
2013/01/09 HTML / CSS
美国智能家居专家:tink
2019/06/04 全球购物
瑞典最大的儿童用品网上商店:pinkorblue.se
2021/03/09 全球购物
商务英语专业求职信范文
2014/01/28 职场文书
光盘行动倡议书
2014/02/02 职场文书
导游词之安徽九华山
2019/09/18 职场文书
MySQL面试题讲解之如何设置Hash索引
2021/11/01 MySQL