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 相关文章推荐
tornado框架blog模块分析与使用
Nov 21 Python
用Python编写web API的教程
Apr 30 Python
详解python实现读取邮件数据并下载附件的实例
Aug 03 Python
Python利用公共键如何对字典列表进行排序详解
May 19 Python
python画图的函数用法以及技巧
Jun 28 Python
Django中自定义查询对象的具体使用
Oct 13 Python
torch 中各种图像格式转换的实现方法
Dec 26 Python
Python 实现向word(docx)中输出
Feb 13 Python
pycharm 更改创建文件默认路径的操作
Feb 15 Python
Python如何在循环内使用list.remove()
Jun 01 Python
python爬虫使用正则爬取网站的实现
Aug 03 Python
Python 操作pdf pdfplumber读取PDF写入Exce
Aug 14 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动态页生成静态页的3种常用方法
2014/11/13 PHP
php中动态调用函数的方法
2015/03/16 PHP
PHP连接MYSQL数据库的3种常用方法
2017/02/27 PHP
LAMP环境使用Composer安装Laravel的方法
2017/03/25 PHP
Javascript与vbscript数据共享
2007/01/09 Javascript
javascript globalStorage类代码
2009/06/04 Javascript
JS中confirm,alert,prompt函数使用区别分析
2010/04/01 Javascript
Jquery实现弹出层分享微博插件具备动画效果
2013/04/03 Javascript
js实现浏览器的各种菜单命令比如打印、查看源文件等等
2013/10/24 Javascript
jQuery DOM操作实例
2014/03/05 Javascript
JavaScript中Function()函数的使用教程
2015/06/04 Javascript
JavaScript实现上下浮动的窗口效果代码
2015/10/12 Javascript
Bootstrap入门书籍之(三)栅格系统
2016/02/17 Javascript
深入理解javascript中concat方法
2016/12/12 Javascript
基于jQuery实现弹幕APP
2017/02/10 Javascript
Vue 父子组件、组件间通信
2017/03/08 Javascript
手机端转换rem适应
2017/04/01 Javascript
详谈JS中数组的迭代方法和归并方法
2017/08/11 Javascript
AngularJS下$http服务Post方法传递json参数的实例
2018/03/29 Javascript
微信小程序 Storage更新详解
2019/07/16 Javascript
Vue + Node.js + MongoDB图片上传组件实现图片预览和删除功能详解
2020/04/29 Javascript
在vue中使用inheritAttrs实现组件的扩展性介绍
2020/12/07 Vue.js
[02:16]深扒TI7聊天轮盘语音出处2
2017/05/11 DOTA
利用Python实现Windows定时关机功能
2017/03/21 Python
python中sort和sorted排序的实例方法
2019/08/26 Python
利用python实现平稳时间序列的建模方式
2020/06/03 Python
python 基于opencv实现图像增强
2020/12/23 Python
Pottery Barn阿联酋:购买家具、家居装饰及更多
2019/12/08 全球购物
环保专项行动方案
2014/05/12 职场文书
2014村书记党建工作汇报材料
2014/11/02 职场文书
关爱空巢老人感想
2015/08/11 职场文书
2016形势与政策学习心得体会
2016/01/12 职场文书
《卧薪尝胆》读后感3篇
2019/12/26 职场文书
Python实现视频中添加音频工具详解
2021/12/06 Python
如何用六步教会你使用python爬虫爬取数据
2022/04/06 Python
WinServer2012搭建DNS服务器的方法步骤
2022/06/10 Servers