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 相关文章推荐
解决python2.7用pip安装包时出现错误的问题
Jan 23 Python
浅谈scrapy 的基本命令介绍
Jun 13 Python
python机器学习理论与实战(五)支持向量机
Jan 19 Python
使用python获取csv文本的某行或某列数据的实例
Apr 03 Python
python之文件读取一行一行的方法
Jul 12 Python
python中pika模块问题的深入探究
Oct 13 Python
Python计算时间间隔(精确到微妙)的代码实例
Feb 26 Python
python实现简单加密解密机制
Mar 19 Python
Python Django Cookie 简单用法解析
Aug 13 Python
django-crontab 定时执行任务方法的实现
Sep 06 Python
matplotlib绘制多子图共享鼠标光标的方法示例
Jan 08 Python
Django url 路由匹配过程详解
Jan 22 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_push 数组函数
2009/12/26 PHP
php中strlen和mb_strlen用法实例分析
2016/11/12 PHP
JavaScript 学习点滴记录
2009/04/24 Javascript
JS 进度条效果实现代码整理
2011/05/21 Javascript
IE不支持getElementsByClassName最终完美解决方案
2012/12/17 Javascript
Jquery 类网页微信二维码图块滚动效果具体实现
2013/10/14 Javascript
浅谈js多维数组和hash数组定义和使用
2016/07/27 Javascript
点击页面任何位置隐藏div的实现方法
2016/09/05 Javascript
Angular页面间切换及传值的4种方法
2016/11/04 Javascript
canvas仿iwatch时钟效果
2017/03/06 Javascript
JavaScript实现购物车基本功能
2017/07/21 Javascript
vue登录页面cookie的使用及页面跳转代码
2019/07/10 Javascript
vue中的mescroll搜索运用及各种填坑处理
2019/10/30 Javascript
[05:26]2014DOTA2西雅图国际邀请赛 iG战队巡礼
2014/07/07 DOTA
[27:39]Ti4 循环赛第二日 LGD vs Fnatic
2014/07/11 DOTA
[06:21]2014DOTA2国际邀请赛 庆祝VG首阶段领跑;B叔为挣牛排半夜整理情报
2014/07/13 DOTA
Python检测网站链接是否已存在
2016/04/07 Python
Django 导出 Excel 代码的实例详解
2017/08/11 Python
python判断字符串是否是json格式方法分享
2017/11/07 Python
python3利用Dlib19.7实现人脸68个特征点标定
2018/02/26 Python
Python通过调用有道翻译api实现翻译功能示例
2018/07/19 Python
Python中dict和set的用法讲解
2019/03/28 Python
详解使用PyInstaller将Pygame库编写的小游戏程序打包为exe文件
2019/08/23 Python
Python爬虫之Selenium鼠标事件的实现
2020/12/04 Python
英国珠宝钟表和家居礼品精品店:David Shuttle
2018/02/24 全球购物
反邪教警示教育方案
2014/05/13 职场文书
关于爱国的标语
2014/06/24 职场文书
大学生安全责任书
2014/07/25 职场文书
2014年除四害工作总结
2014/12/06 职场文书
2014年学校总务处工作总结
2014/12/08 职场文书
2015年度个人教学工作总结
2015/05/20 职场文书
幼儿园托班教育随笔
2015/08/14 职场文书
红领巾广播站广播稿
2015/08/19 职场文书
告诉你创业计划书的8个实用技巧
2019/07/12 职场文书
python munch库的使用解析
2021/05/25 Python
2021年国漫热度排行前十,完美世界上榜,第四是美国动画作品
2022/03/18 国漫