learn_requests
# -*- coding: utf-8 -*-
import requests URL_IP = 'http://localhost:8000/ip'
URL_GET = 'http://localhost:8000/get' def use_simple_requests():
response = requests.get(URL_IP)
print '>>>>Response Headers:'
print response.headers
print '>>>>Response body:'
print response.text def use_params_requests():
params = {'param1': 'hello', 'param2': 'world'}
response = requests.get(URL_GET, params=params)
print '>>>>Response Headers:'
print response.headers
print '>>>>Status Code:'
print response.status_code
print '>>>>Reason:'
print response.reason
print '>>>>Request body:'
print response.text if __name__ == '__main__':
print '>>>Use simple requests:'
use_simple_requests()
print ''
print '>>>Use params requests:'
use_params_requests()
# -*- coding: utf-8 -*-
import urllib
import urllib2 URL_IP = 'http://localhost:8000/ip'
URL_GET = 'http://localhost:8000/get' def use_simple_urllib2():
response = urllib2.urlopen(URL_IP)
print '>>>>Response Headers:'
print response.info()
print '>>>>Response body:'
print ''.join([line for line in response.readlines()]) def use_params_urllib2():
params = urllib.urlencode({'param1': 'hello', 'param2': 'world'})
response = urllib2.urlopen('?'.join([URL_GET, '%s']) % params)
print '>>>>Response Headers:'
print response.info()
print '>>>>Status Code:'
print response.getcode()
print '>>>>Request body:'
print ''.join([line for line in response.readlines()]) if __name__ == '__main__':
print '>>>Use simple urllib2:'
use_simple_urllib2()
print ''
print '>>>Use params urllib2:'
use_params_urllib2()
# -*- coding: utf-8 -*-
import json
import requests
from requests import exceptions URL = 'https://api.github.com' def build_uri(endpoint):
return '/'.join([URL, endpoint]) def better_print(json_str):
return json.dumps(json.loads(json_str), indent=4) def request_method():
response = requests.get(build_uri('user/emails'), auth=('imoocdemo', 'imoocdemo123'))
print better_print(response.text) def params_request():
response = requests.get(build_uri('users'), params={'since': 11})
print better_print(response.text)
print response.request.headers
print response.url def json_request():
# response = requests.patch(build_uri('user'), auth=('imoocdemo', 'imoocdemo123'), json={'name': 'babymooc2', 'email': 'hello-world@imooc.org'})
response = requests.post(build_uri('user/emails'), auth=('imoocdemo', 'imoocdemo123'), json=['helloworld@github.com'])
print better_print(response.text)
print response.request.headers
print response.request.body
print response.status_code def timeout_request():
try:
response = requests.get(build_uri('user/emails'), timeout=10)
response.raise_for_status()
except exceptions.Timeout as e:
print e.message
except exceptions.HTTPError as e:
print e.message
else:
print response.text
print response.status_code def hard_requests():
from requests import Request, Session
s = Session()
headers = {'User-Agent': 'fake1.3.4'}
req = Request('GET', build_uri('user/emails'), auth=('imoocdemo', 'imoocdemo123'), headers=headers)
prepped = req.prepare()
print prepped.body
print prepped.headers resp = s.send(prepped, timeout=5)
print resp.status_code
print resp.request.headers
print resp.text if __name__ == '__main__':
hard_requests()
# -*- coding: utf-8 -*-
import requests response = requests.get('https://api.github.com')
print "状态码,具体解释"
print response.status_code, response.reason
print "头部信息"
print response.headers
print "URL 信息"
print response.url
print "redirect 信息"
print response.history
print "耗费时长"
print response.elapsed
print "request 信息"
print response.request.method print '----------------------' print "编码信息"
print response.encoding
print "消息主体内容: byte"
print response.content, type(response.content)
print "消息主体内容: 解析"
print response.text, type(response.text)
print "消息主体内容"
print response.json(), type(response.json())
# -*- coding: utf-8 -*-
import requests def get_key_info(response, *args, **kwargs):
"""回调函数
"""
print response.headers['Content-Type'] def main():
"""主程序
"""
requests.get('https://api.github.com', hooks=dict(response=get_key_info)) main()
# -*- coding: utf -*-
import requests def download_image():
"""demo: 下载图片, 文件
"""
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36'}
url = "http://img3.imgtn.bdimg.com/it/u=2228635891,3833788938&fm=21&gp=0.jpg"
response = requests.get(url, headers=headers, stream=True)
with open('demo.jpg', 'wb') as fd:
for chunk in response.iter_content(128):
fd.write(chunk) def download_image_improved():
"""demo: 下载图片
"""
# 伪造headers信息
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36'}
# 限定url
url = "http://img3.imgtn.bdimg.com/it/u=2228635891,3833788938&fm=21&gp=0.jpg"
response = requests.get(url, headers=headers, stream=True)
from contextlib import closing
with closing(requests.get(url, headers=headers, stream=True)) as response:
# 打开文件
with open('demo1.jpg', 'wb') as fd:
# 每128写入一次
for chunk in response.iter_content(128):
fd.write(chunk) download_image_improved()
session和cookie
from:http://www.imooc.com/learn/736
learn_requests的更多相关文章
随机推荐
- python---基础知识回顾(四)(模块sys,os,random,hashlib,re,序列化json和pickle,xml,shutil,configparser,logging,datetime和time,其他)
前提:dir,__all__,help,__doc__,__file__ dir:可以用来查看模块中的所有特性(函数,类,变量等) >>> import copy >>& ...
- maven 依赖、聚合和继承 (转)
Maven 插件和仓库 Maven 本质上是一个插件框架,它的核心并不执行任何具体的构建任务,仅仅定义了抽象的生命周期,所有这些任务都交给插件来完成的.每个插件都能完成至少一个任务,每个任务即是一个功 ...
- Python学习笔记(四十)— 内置模块(9)HTMLParser
摘抄自:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001432002312 ...
- AES Java加密 C#解密 (128-ECB加密模式)
在项目中遇到这么一个问题: java端需要把一些数据AES加密后传给C#端,找了好多资料,算是解决了,分享一下: import sun.misc.BASE64Decoder; import sun.m ...
- ASP.Net中自定义Http处理及应用之HttpModule篇
HttpHandler实现了类似于ISAPI Extention的功能,他处理请求(Request)的信息和发送响应(Response).HttpHandler功能的实现通过实现IHttpHandle ...
- 51nod 1140 矩阵相乘结果的判断
给出三个N*N的矩阵A, B, C,问A * B是否等于C? Input 第1行,1个数N.(0 <= N <= 500) 第2 - N + 1行:每行N个数,对应矩阵A的元素.(0 ...
- js写弹窗
1.先来看弹窗的模样 点击“弹出窗口”后会弹出下面窗口 2.下面是实现弹出窗口的代码,其中引入的jquery一般自己有,没有的话可以从网上下载.tanchuang.js和tanchuang.css写在 ...
- 浅析 Spring Aop
aop也是Spring里比较重要的一个点,最近把源码看了下,这里总结一下 使用上主要就下面的点注意下: 相关的Annotaion Around Before After AfterReturning ...
- 【leetcode 简单】第十三题 最大子序和
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和. 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: 连续子数组 ...
- Django之动态验证码的生成
kind.html <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...