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实现3行代码解简单的一元一次方程
Aug 18 Python
Python实现的彩票机选器实例
Jun 17 Python
Python实现TCP/IP协议下的端口转发及重定向示例
Jun 14 Python
python安装Scrapy图文教程
Aug 14 Python
python3.6 实现AES加密的示例(pyCryptodome)
Jan 10 Python
简单的python协同过滤程序实例代码
Jan 31 Python
pandas.cut具体使用总结
Jun 24 Python
Python爬虫图片懒加载技术 selenium和PhantomJS解析
Sep 18 Python
python中线程和进程有何区别
Jun 17 Python
python报错: 'list' object has no attribute 'shape'的解决
Jul 15 Python
Pytorch反向传播中的细节-计算梯度时的默认累加操作
Jun 05 Python
python数字图像处理:图像的绘制
Jun 28 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
让这部DC动画新作刷新你的认知
2020/03/03 欧美动漫
汉字转化为拼音(php版)
2006/10/09 PHP
PHP 和 MySQL 基础教程(三)
2006/10/09 PHP
在smarty模板中使用PHP函数的方法
2011/04/23 PHP
php 的加密函数 md5,crypt,base64_encode 等使用介绍
2012/04/09 PHP
PHP面向对象——访问修饰符介绍
2012/11/08 PHP
分享PHP函数实现数字与文字分页代码
2015/07/28 PHP
php抽象类和接口知识点整理总结
2019/08/02 PHP
深入document.write()与HTML4.01的非成对标签的详解
2013/05/08 Javascript
chrome下img加载对height()的影响示例探讨
2014/05/26 Javascript
基于jQuery实现点击弹出层实例代码
2016/01/01 Javascript
Bootstrap table分页问题汇总
2016/05/30 Javascript
js实现漫天星星效果
2017/01/19 Javascript
vuejs通过filterBy、orderBy实现搜索筛选、降序排序数据
2020/10/26 Javascript
原生js实现放大镜
2017/02/20 Javascript
bootstrap的工具提示实例代码
2017/05/17 Javascript
vue全局组件与局部组件使用方法详解
2018/03/29 Javascript
详解Vue 动态组件与全局事件绑定总结
2018/11/11 Javascript
jQuery实现高级检索功能
2019/05/28 jQuery
node运行js获得输出的三种方式示例详解
2020/07/02 Javascript
详解Vue之事件处理
2020/07/10 Javascript
Vue使用轮询定时发送请求代码
2020/08/10 Javascript
使用JS实现鼠标放上图片进行放大离开实现缩小功能
2021/01/27 Javascript
python 获取当前目录下的文件目录和文件名实例代码详解
2020/03/10 Python
Python内存映射文件读写方式
2020/04/24 Python
python中@contextmanager实例用法
2021/02/07 Python
草莓网化妆品澳大利亚站:Strawberrynet AU
2017/12/18 全球购物
夏尔巴人登珠峰品牌:Sherpa Adventure Gear
2018/02/08 全球购物
联想英国官网:Lenovo英国
2019/07/17 全球购物
幼儿教师自我鉴定
2013/11/02 职场文书
创业计划书模版
2014/02/05 职场文书
新闻专业毕业生英文求职信
2014/03/19 职场文书
幼儿园的门卫岗位职责
2014/04/10 职场文书
2014年学雷锋活动总结
2014/06/26 职场文书
中班下学期幼儿评语
2014/12/30 职场文书
redis中lua脚本使用教程
2021/11/01 Redis