python的强大之处在于提供了很多的标准库,这些标准库可以直接调用,本节部分,重点学习和总结在

接口测试中Python的Http请求的库的学习。

首先来看httplib,官方的解释为:本模块定义了类实现客户端的 HTTP 和 HTTPS 协议。它通常不能直接

使用 — — 模块 urllib 用于处理使用 HTTP 和 HTTPS 的 Url。使用httplib来做一个简单的对百度的请求,看

这样的一个实现过程,见实现的代码:

#!/usr/bin/env python
#coding:utf-8 import httplib def getBaidu():
'''对百度发送一个GET请求'''
http_client=httplib.HTTPConnection('baidu.com',80,timeout=20)
http_client.request('GET','')
r=http_client.getresponse()
print r.status
print r.read() getBaidu()

这里我们详细的来看r提供了那些方法,见输出的结果:

#!/usr/bin/env python
#coding:utf-8 import httplib def getBaidu():
'''对百度发送一个GET请求'''
http_client=httplib.HTTPConnection('baidu.com',80,timeout=20)
http_client.request('GET','')
r=http_client.getresponse()
print dir(r) getBaidu()
C:\Python27\python.exe D:/git/Python/bookDay/api/http/httplipTest.py
['__doc__', '__init__', '__module__', '_check_close', '_method', '_read_chunked', '_read_status', '_safe_read', 'begin', 'chunk_left', 'chunked', 'close', 'debuglevel', 'fileno', 'fp', 'getheader', 'getheaders', 'isclosed', 'length', 'msg', 'read', 'reason', 'status', 'strict', 'version', 'will_close'] Process finished with exit code 0

使用dir(r)方法可以看到调用的方法,如我们想看到请求百度这样的一个GET请求,到底返回的status code是多少,

是否OK,响应内容是什么,headers是什么,见实现的代码和输出的内容:

#!/usr/bin/env python
#coding:utf-8 import httplib def getBaidu():
'''对百度发送一个GET请求'''
http_client=httplib.HTTPConnection('www.baidu.com',80,timeout=20)
http_client.request('GET','/')
r=http_client.getresponse()
print u'状态的状态码:\n',r.status
print u'是否请求Ok:\n',r.reason
print u'header是多少:\n',r.getheaders()
print u'Response消息结构:\n',r.msg
print u'响应内容:\n',r.read() getBaidu()

见输出的结果内容:

C:\Python27\python.exe D:/git/Python/bookDay/api/http/httplipTest.py
状态的状态码:
200
是否请求Ok:
OK
header是多少:
[('content-length', '14613'), ('set-cookie', 'BAIDUID=5BE300935709382ADC6AFA01D08E1959:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com, BIDUPSID=5BE300935709382ADC6AFA01D08E1959; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com, PSTM=1481724972; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com'), ('accept-ranges', 'bytes'), ('vary', 'Accept-Encoding'), ('server', 'BWS/1.1'), ('last-modified', 'Mon, 12 Dec 2016 06:09:00 GMT'), ('connection', 'Keep-Alive'), ('x-ua-compatible', 'IE=Edge,chrome=1'), ('pragma', 'no-cache'), ('cache-control', 'no-cache'), ('date', 'Wed, 14 Dec 2016 14:16:12 GMT'), ('p3p', 'CP=" OTI DSP COR IVA OUR IND COM "'), ('content-type', 'text/html')]
Response消息结构:
Date: Wed, 14 Dec 2016 14:16:12 GMT
Content-Type: text/html
Content-Length: 14613
Last-Modified: Mon, 12 Dec 2016 06:09:00 GMT
Connection: Keep-Alive
Vary: Accept-Encoding
Set-Cookie: BAIDUID=5BE300935709382ADC6AFA01D08E1959:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: BIDUPSID=5BE300935709382ADC6AFA01D08E1959; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: PSTM=1481724972; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
P3P: CP=" OTI DSP COR IVA OUR IND COM "
Server: BWS/1.1
X-UA-Compatible: IE=Edge,chrome=1
Pragma: no-cache
Cache-control: no-cache
Accept-Ranges: bytes 响应内容:
<!DOCTYPE html><!--STATUS OK-->
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<link rel="dns-prefetch" href="//s1.bdstatic.com"/>
<link rel="dns-prefetch" href="//t1.baidu.com"/>
<link rel="dns-prefetch" href="//t2.baidu.com"/>
<link rel="dns-prefetch" href="//t3.baidu.com"/>
<link rel="dns-prefetch" href="//t10.baidu.com"/>
<link rel="dns-prefetch" href="//t11.baidu.com"/>
<link rel="dns-prefetch" href="//t12.baidu.com"/>
<link rel="dns-prefetch" href="//b1.bdstatic.com"/>
<title>百度一下,你就知道</title>
<link href="http://s1.bdstatic.com/r/www/cache/static/home/css/index.css" rel="stylesheet" type="text/css" />
<!--[if lte IE 8]><style index="index" >#content{height:480px\9}#m{top:260px\9}</style><![endif]-->
<!--[if IE 8]><style index="index" >#u1 a.mnav,#u1 a.mnav:visited{font-family:simsun}</style><![endif]-->
<script>var hashMatch = document.location.href.match(/#+(.*wd=[^&].+)/);if (hashMatch && hashMatch[0] && hashMatch[1]) {document.location.replace("http://"+location.host+"/s?"+hashMatch[1]);}var ns_c = function(){};</script>
<script>function h(obj){obj.style.behavior='url(#default#homepage)';var a = obj.setHomePage('//www.baidu.com/');}</script>
<noscript><meta http-equiv="refresh" content="0; url=/baidu.html?from=noscript"/></noscript>
<script>window._ASYNC_START=new Date().getTime();</script>
</head>
<body link="#0000cc"><div id="wrapper" style="display:none;"><div id="u"><a href="//www.baidu.com/gaoji/preferences.html" onmousedown="return user_c({'fm':'set','tab':'setting','login':'0'})">搜索设置</a>|<a id="btop" href="/" onmousedown="return user_c({'fm':'set','tab':'index','login':'0'})">百度首页</a>|<a id="lb" href="https://passport.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" onclick="return false;" onmousedown="return user_c({'fm':'set','tab':'login'})">登录</a><a href="https://passport.baidu.com/v2/?reg&regType=1&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" onmousedown="return user_c({'fm':'set','tab':'reg'})" target="_blank" class="reg">注册</a></div><div id="head"><div class="s_nav"><a href="/" class="s_logo" onmousedown="return c({'fm':'tab','tab':'logo'})"><img src="//www.baidu.com/img/baidu_jgylogo3.gif" width="117" height="38" border="0" alt="到百度首页" title="到百度首页"></a><div class="s_tab" id="s_tab"><a href="http://news.baidu.com/ns?cl=2&rn=20&tn=news&word=" wdfield="word" onmousedown="return c({'fm':'tab','tab':'news'})">新闻</a> <b>网页</b> <a href="http://tieba.baidu.com/f?kw=&fr=wwwt" wdfield="kw" onmousedown="return c({'fm':'tab','tab':'tieba'})">贴吧</a> <a href="http://zhidao.baidu.com/q?ct=17&pn=0&tn=ikaslist&rn=10&word=&fr=wwwt" wdfield="word" onmousedown="return c({'fm':'tab','tab':'zhidao'})">知道</a> <a href="http://music.baidu.com/search?fr=ps&key=" wdfield="key" onmousedown="return c({'fm':'tab','tab':'music'})">音乐</a> <a href="http://image.baidu.com/i?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&word=" wdfield="word" onmousedown="return c({'fm':'tab','tab':'pic'})">图片</a> <a href="http://v.baidu.com/v?ct=301989888&rn=20&pn=0&db=0&s=25&word=" wdfield="word" onmousedown="return c({'fm':'tab','tab':'video'})">视频</a> <a href="http://map.baidu.com/m?word=&fr=ps01000" wdfield="word" onmousedown="return c({'fm':'tab','tab':'map'})">地图</a> <a href="http://wenku.baidu.com/search?word=&lm=0&od=0" wdfield="word" onmousedown="return c({'fm':'tab','tab':'wenku'})">文库</a> <a href="//www.baidu.com/more/" onmousedown="return c({'fm':'tab','tab':'more'})">更多»</a></div></div><form id="form" name="f" action="/s" class="fm" ><input type="hidden" name="ie" value="utf-8"><input type="hidden" name="f" value="8"><input type="hidden" name="rsv_bp" value="1"><span class="bg s_ipt_wr"><input name="wd" id="kw" class="s_ipt" value="" maxlength="100"></span><span class="bg s_btn_wr"><input type="submit" id="su" value="百度一下" class="bg s_btn" onmousedown="this.className='bg s_btn s_btn_h'" onmouseout="this.className='bg s_btn'"></span><span class="tools"><span id="mHolder"><div id="mCon"><span>输入法</span></div><ul id="mMenu"><li><a href="javascript:;" name="ime_hw">手写</a></li><li><a href="javascript:;" name="ime_py">拼音</a></li><li class="ln"></li><li><a href="javascript:;" name="ime_cl">关闭</a></li></ul></span><span class="shouji"><strong>推荐&nbsp;:&nbsp;</strong><a href="http://w.x.baidu.com/go/mini/8/10000020" onmousedown="return ns_c({'fm':'behs','tab':'bdbrowser'})">百度浏览器,打开网页快2秒!</a></span></span></form></div><div id="content"><div id="u1"><a href="http://news.baidu.com" name="tj_trnews" class="mnav">新闻</a><a href="http://www.hao123.com" name="tj_trhao123" class="mnav">hao123</a><a href="http://map.baidu.com" name="tj_trmap" class="mnav">地图</a><a href="http://v.baidu.com" name="tj_trvideo" class="mnav">视频</a><a href="http://tieba.baidu.com" name="tj_trtieba" class="mnav">贴吧</a><a href="https://passport.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" name="tj_login" id="lb" onclick="return false;">登录</a><a href="//www.baidu.com/gaoji/preferences.html" name="tj_settingicon" id="pf">设置</a><a href="//www.baidu.com/more/" name="tj_briicon" id="bri">更多产品</a></div><div id="m"><p id="lg"><img src="//www.baidu.com/img/bd_logo.png" width="270" height="129"></p><p id="nv"><a href="http://news.baidu.com">新&nbsp;闻</a> <b>网&nbsp;页</b> <a href="http://tieba.baidu.com">贴&nbsp;吧</a> <a href="http://zhidao.baidu.com">知&nbsp;道</a> <a href="http://music.baidu.com">音&nbsp;乐</a> <a href="http://image.baidu.com">图&nbsp;片</a> <a href="http://v.baidu.com">视&nbsp;频</a> <a href="http://map.baidu.com">地&nbsp;图</a></p><div id="fm"><form id="form1" name="f1" action="/s" class="fm"><span class="bg s_ipt_wr"><input type="text" name="wd" id="kw1" maxlength="100" class="s_ipt"></span><input type="hidden" name="rsv_bp" value="0"><input type=hidden name=ch value=""><input type=hidden name=tn value="baidu"><input type=hidden name=bar value=""><input type="hidden" name="rsv_spt" value="3"><input type="hidden" name="ie" value="utf-8"><span class="bg s_btn_wr"><input type="submit" value="百度一下" id="su1" class="bg s_btn" onmousedown="this.className='bg s_btn s_btn_h'" onmouseout="this.className='bg s_btn'"></span></form><span class="tools"><span id="mHolder1"><div id="mCon1"><span>输入法</span></div></span></span><ul id="mMenu1"><div class="mMenu1-tip-arrow"><em></em><ins></ins></div><li><a href="javascript:;" name="ime_hw">手写</a></li><li><a href="javascript:;" name="ime_py">拼音</a></li><li class="ln"></li><li><a href="javascript:;" name="ime_cl">关闭</a></li></ul></div><p id="lk"><a href="http://baike.baidu.com">百科</a> <a href="http://wenku.baidu.com">文库</a> <a href="http://www.hao123.com">hao123</a><span>&nbsp;|&nbsp;<a href="//www.baidu.com/more/">更多&gt;&gt;</a></span></p><p id="lm"></p></div></div><div id="ftCon"><div id="ftConw"><p id="lh"><a id="seth" onClick="h(this)" href="/" onmousedown="return ns_c({'fm':'behs','tab':'homepage','pos':0})">把百度设为主页</a><a id="setf" href="//www.baidu.com/cache/sethelp/index.html" onmousedown="return ns_c({'fm':'behs','tab':'favorites','pos':0})" target="_blank">把百度设为主页</a><a onmousedown="return ns_c({'fm':'behs','tab':'tj_about'})" href="http://home.baidu.com">关于百度</a><a onmousedown="return ns_c({'fm':'behs','tab':'tj_about_en'})" href="http://ir.baidu.com">About Baidu</a></p><p id="cp">&copy;2014&nbsp;Baidu&nbsp;<a href="/duty/" name="tj_duty">使用百度前必读</a>&nbsp;京ICP证030173号&nbsp;<img src="http://s1.bdstatic.com/r/www/cache/static/global/img/gs_237f015b.gif"></p></div></div><div id="wrapper_wrapper"></div></div><div class="c-tips-container" id="c-tips-container"></div>
<script>window.__async_strategy=2;</script>
<script>var bds={se:{},su:{urdata:[],urSendClick:function(){}},util:{},use:{},comm : {domain:"http://www.baidu.com",ubsurl : "http://sclick.baidu.com/w.gif",tn:"baidu",queryEnc:"",queryId:"",inter:"",templateName:"baidu",sugHost : "http://suggestion.baidu.com/su",query : "",qid : "",cid : "",sid : "",indexSid : "",stoken : "",serverTime : "",user : "",username : "",loginAction : [],useFavo : "",pinyin : "",favoOn : "",curResultNum:"",rightResultExist:false,protectNum:0,zxlNum:0,pageNum:1,pageSize:10,newindex:0,async:1,maxPreloadThread:5,maxPreloadTimes:10,preloadMouseMoveDistance:5,switchAddMask:false,isDebug:false,ishome : 1},_base64:{domain : "http://b1.bdstatic.com/",b64Exp : -1,pdc : 0}};var name,navigate,al_arr=[];var selfOpen = window.open;eval("var open = selfOpen;");var isIE=navigator.userAgent.indexOf("MSIE")!=-1&&!window.opera;var E = bds.ecom= {};bds.se.mon = {'loadedItems':[],'load':function(){},'srvt':-1};try {bds.se.mon.srvt = parseInt(document.cookie.match(new RegExp("(^| )BDSVRTM=([^;]*)(;|$)"))[2]);document.cookie="BDSVRTM=;expires=Sat, 01 Jan 2000 00:00:00 GMT"; }catch(e){}</script>
<script>if(!location.hash.match(/[^a-zA-Z0-9]wd=/)){document.getElementById("ftCon").style.display='block';document.getElementById("u1").style.display='block';document.getElementById("content").style.display='block';document.getElementById("wrapper").style.display='block';setTimeout(function(){try{document.getElementById("kw1").focus();document.getElementById("kw1").parentNode.className += ' iptfocus';}catch(e){}},0);}</script>
<script type="text/javascript" src="http://s1.bdstatic.com/r/www/cache/static/jquery/jquery-1.10.2.min_f2fb5194.js"></script>
<script>(function(){var index_content = $('#content');var index_foot= $('#ftCon');var index_css= $('head [index]');var index_u= $('#u1');var result_u= $('#u');var wrapper=$("#wrapper");window.index_on=function(){index_css.insertAfter("meta:eq(0)");result_common_css.remove();result_aladdin_css.remove();result_sug_css.remove();index_content.show();index_foot.show();index_u.show();result_u.hide();wrapper.show();if(bds.su&&bds.su.U&&bds.su.U.homeInit){bds.su.U.homeInit();}setTimeout(function(){try{$('#kw1').get(0).focus();window.sugIndex.start();}catch(e){}},0);if(typeof initIndex=='function'){initIndex();}};window.index_off=function(){index_css.remove();index_content.hide();index_foot.hide();index_u.hide();result_u.show();result_aladdin_css.insertAfter("meta:eq(0)");result_common_css.insertAfter("meta:eq(0)");result_sug_css.insertAfter("meta:eq(0)");wrapper.show();};})();</script>
<script>window.__switch_add_mask=1;</script>
<script type="text/javascript" src="http://s1.bdstatic.com/r/www/cache/static/global/js/instant_search_newi_redirect1_20bf4036.js"></script>
<script>initPreload();$("#u,#u1").delegate("#lb",'click',function(){try{bds.se.login.open();}catch(e){}});if(navigator.cookieEnabled){document.cookie="NOJS=;expires=Sat, 01 Jan 2000 00:00:00 GMT";}</script>
<script>$(function(){for(i=0;i<3;i++){u($($('.s_ipt_wr')[i]),$($('.s_ipt')[i]),$($('.s_btn_wr')[i]),$($('.s_btn')[i]));}function u(iptwr,ipt,btnwr,btn){if(iptwr && ipt){iptwr.on('mouseover',function(){iptwr.addClass('ipthover');}).on('mouseout',function(){iptwr.removeClass('ipthover');}).on('click',function(){ipt.focus();});ipt.on('focus',function(){iptwr.addClass('iptfocus');}).on('blur',function(){iptwr.removeClass('iptfocus');}).on('render',function(e){var $s = iptwr.parent().find('.bdsug');var l = $s.find('li').length;if(l>=5){$s.addClass('bdsugbg');}else{$s.removeClass('bdsugbg');}});}if(btnwr && btn){btnwr.on('mouseover',function(){btn.addClass('btnhover');}).on('mouseout',function(){btn.removeClass('btnhover');});}}});</script>
<script type="text/javascript" src="http://s1.bdstatic.com/r/www/cache/static/home/js/bri_7f1fa703.js"></script>
<script>(function(){var _init=false;window.initIndex=function(){if(_init){return;}_init=true;var w=window,d=document,n=navigator,k=d.f1.wd,a=d.getElementById("nv").getElementsByTagName("a"),isIE=n.userAgent.indexOf("MSIE")!=-1&&!window.opera;(function(){if(/q=([^&]+)/.test(location.search)){k.value=decodeURIComponent(RegExp["\x241"])}})();(function(){var u = G("u1").getElementsByTagName("a"), nv = G("nv").getElementsByTagName("a"), lk = G("lk").getElementsByTagName("a"), un = "";var tj_nv = ["news","tieba","zhidao","mp3","img","video","map"];var tj_lk = ["baike","wenku","hao123","more"];un = bds.comm.user == "" ? "" : bds.comm.user;function _addTJ(obj){addEV(obj, "mousedown", function(e){var e = e || window.event;var target = e.target || e.srcElement;if(target.name){ns_c({'fm':'behs','tab':target.name,'un':encodeURIComponent(un)});}});}for(var i = 0; i < u.length; i++){_addTJ(u[i]);}for(var i = 0; i < nv.length; i++){nv[i].name = 'tj_' + tj_nv[i];}for(var i = 0; i < lk.length; i++){lk[i].name = 'tj_' + tj_lk[i];}})();(function() {var links = {'tj_news': ['word', 'http://news.baidu.com/ns?tn=news&cl=2&rn=20&ct=1&ie=utf-8'],'tj_tieba': ['kw', 'http://tieba.baidu.com/f?ie=utf-8'],'tj_zhidao': ['word', 'http://zhidao.baidu.com/search?pn=0&rn=10&lm=0'],'tj_mp3': ['key', 'http://music.baidu.com/search?fr=ps&ie=utf-8'],'tj_img': ['word', 'http://image.baidu.com/i?ct=201326592&cl=2&nc=1&lm=-1&st=-1&tn=baiduimage&istype=2&fm=&pv=&z=0&ie=utf-8'],'tj_video': ['word', 'http://video.baidu.com/v?ct=301989888&s=25&ie=utf-8'],'tj_map': ['wd', 'http://map.baidu.com/?newmap=1&ie=utf-8&s=s'],'tj_baike': ['word', 'http://baike.baidu.com/search/word?pic=1&sug=1&enc=utf8'],'tj_wenku': ['word', 'http://wenku.baidu.com/search?ie=utf-8']};var domArr = [G('nv'), G('lk'),G('cp')],kw = G('kw1');for (var i = 0, l = domArr.length; i < l; i++) {domArr[i].onmousedown = function(e) {e = e || window.event;var target = e.target || e.srcElement,name = target.getAttribute('name'),items = links[name],reg = new RegExp('^\\s+|\\s+\x24'),key = kw.value.replace(reg, '');if (items) {if (key.length > 0) {var wd = items[0], url = items[1],url = url + ( name === 'tj_map' ? encodeURIComponent('&' + wd + '=' + key) : ( ( url.indexOf('?') > 0 ? '&' : '?' ) + wd + '=' + encodeURIComponent(key) ) );target.href = url;} else {target.href = target.href.match(new RegExp('^http:\/\/.+\.baidu\.com'))[0];}}name && ns_c({'fm': 'behs','tab': name,'query': encodeURIComponent(key),'un': encodeURIComponent(bds.comm.user || '') });};}})();};if(window.pageState==0){initIndex();}})();document.cookie = 'IS_STATIC=1;expires=' + new Date(new Date().getTime() + 10*60*1000).toGMTString();</script>
</body></html> Process finished with exit code 0

下来来看urllib2的库,看官方的解释:urllib2 定义了很多函数和类,这些函数和类能够帮助我们在复杂的情况下获取URLS内容。

复杂情况— 基本的和深入的验证, 重定向, cookies 等等.和如上一样,我们使用urllib2来实现对百度的请求,见GET请求的代码:

#!/usr/bin/env python
#coding:utf-8 import urllib
import urllib2 def get_baidu():
r=urllib2.urlopen('http://www.baidu.com')
print u'Response code:\n',r.getcode(),r.msg
print u'headers:\n',r.headers get_baidu()

见输出结果的内容:

C:\Python27\python.exe D:/git/Python/bookDay/api/http/httplipTest.py
Response code:
200 OK
headers:
Date: Wed, 14 Dec 2016 14:52:28 GMT
Content-Type: text/html; charset=utf-8
Vary: Accept-Encoding
Set-Cookie: BAIDUID=55980CB92E6F9F88BF0FF2B73E8607D4:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: BIDUPSID=55980CB92E6F9F88BF0FF2B73E8607D4; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: PSTM=1481727148; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com
Set-Cookie: BDSVRTM=0; path=/
Set-Cookie: BD_HOME=0; path=/
Set-Cookie: H_PS_PSSID=1429_21422_21120_21553_21408_20927; path=/; domain=.baidu.com
P3P: CP=" OTI DSP COR IVA OUR IND COM "
Cache-Control: private
Cxy_all: baidu+435ac15289339958b4bcff45cd341d25
Expires: Wed, 14 Dec 2016 14:51:52 GMT
X-Powered-By: HPHP
Server: BWS/1.1
X-UA-Compatible: IE=Edge,chrome=1
BDPAGETYPE: 1
BDQID: 0xfc9210c000017b10
BDUSERID: 0
Transfer-Encoding: chunked
Proxy-Connection: Close

下面使用urllib2实现一个POST的请求过程,见实现的代码:

#!/usr/bin/env python
#coding:utf-8 import urllib
import urllib2 def get_baidu():
r=urllib2.urlopen('http://www.baidu.com')
print u'Response code:\n',r.getcode(),r.msg
print u'headers:\n',r.headers def post_cun():
params=urllib.urlencode({'cityId':'438'})
r=urllib2.urlopen('http://m.cyw.com/index.php?m=api&c=cookie&a=setcity',params)
print r.getcode(),r.msg
print
r.read() post_cun()

见输出结果的json内容:

C:\Python27\python.exe D:/git/Python/bookDay/api/http/httplipTest.py
200 OK
{"status":true,"homeUrl":"\/xian"}
坚持就是一种赢姿态!

python接口测试之Http请求(三)的更多相关文章

  1. python接口测试之mock(二)

    上一篇对mock-server已经做了初步的介绍,今天这里继续接着之前的介绍进行,我们先看之前的mock-server部分,之前编写了一个登录的mock,具体json文件见如下的内容: 小王子1110 ...

  2. python接口自动化9-https请求(SSL)

    前言 本来最新的requests库V2.13.0是支持https请求的,但是一般写脚本时候,我们会用抓包工具fiddler,这时候会报:requests.exceptions.SSLError: [S ...

  3. python接口测试之mock(三)

    前面介绍了moco的详细的使用,它主要是基于moco-runner-0.11.0-standalone.jar,通过编写json的文件来实现,mock翻译过来就是模拟的意思,也就是说,它是将测试对象所 ...

  4. python接口测试之新手篇

    嗨,大家好,我是小白,好久没写博客了,最近公司搞什么python的接口测试,心里一阵狂喜,在公司上百个接口里拿出一个主要接口一顿乱搞,好在搞通了 但是在这过程中也碰到了好多的问题,决定将问题分享出来能 ...

  5. python接口自动化-post请求3

    一.SSL 证书 https 的请求相对于http安全级别高,需要验证SSL证书import urllib3 使用这个方法就可以了urllib3.disable_warnings() 可忽略警告 二. ...

  6. python接口自动化-post请求1

    一.查看官方文档 1. 学习一个新的模块,直接用 help 函数就能查看相关注释或案例内容,例如 具体信息如下,可查看 python 发送 ge t和 post 请求的案例: F:\test-req- ...

  7. Jmeter接口测试之Get请求

    [一] 在测试计划下面添加一个线程组---------->在线程组下面分别添加HTTP请求.响应断言.BeanShellPreProcessor.察看结果树.聚合报告等内容. [二] 将使用的协 ...

  8. python接口自动化9-https请求(SSL)【转载】

    本篇转自博客:上海-悠悠 原文地址:http://www.cnblogs.com/yoyoketang/tag/python%E6%8E%A5%E5%8F%A3%E8%87%AA%E5%8A%A8%E ...

  9. Python接口测试之moco

    在现在的软件开发过程中,特别是app的部分,需要的很多数据以及内容,都是来自server端的API,但是不能保证 在客户端开发的时候,api在server端已经开发完成,专门等着前端来调用,理想的情况 ...

随机推荐

  1. python的Debug调试

    先打开Shell的Debug-->Debugger调试, 然后点击程序的运行 点击Debug的step按钮查看每一步的结果

  2. urllib的高级用法

    Handler简介 我们可以把他理解为各种处理器,有专门处理登录验证的,有处理cookies的,有处理代理设置的.利用他们,我们几乎可以做到HTTP请求中的所有事情. 首先,介绍一下 urllib.r ...

  3. Android推送服务(1)几种实现方式

    1.几种常见的解决方案实现原理 1)轮询(Pull)方式:应用程序应当阶段性的与服务器进行连接并查询是否有新的消息到达,你必须自己实现与服务器之间的通信,例如消息排队等.而且你还要考虑轮询的频率,如果 ...

  4. GUID的学习

    GUID(全局统一标识符)是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的.通常平台会提供生成GUID的API.生成算法很有意思,用到了以太网卡地址.纳秒级时间.芯片ID码和许多可 ...

  5. 443 String Compression 压缩字符串

    给定一组字符,使用原地算法将其压缩.压缩后的长度必须始终小于或等于原数组长度.数组的每个元素应该是长度为1 的字符(不是 int 整数类型).在完成原地修改输入数组后,返回数组的新长度.进阶:你能否仅 ...

  6. libtool版本过新的问题

      安装过程中出现: libtool: Version mismatch error. This is libtool 2.4.2, but the libtool: definition of th ...

  7. Html标签杂记

    <html> <head> <title> </title> </head> <body> </body> < ...

  8. SSM Note

    1.获取项目的绝对路径:${pageContext.request.contextPath } 2.销毁session:session.invalidate(); 3.控制器接收前端参数时,参数名要与 ...

  9. AJPFX总结泛型概念和使用

    泛型泛型(generic)概述和基本使用                泛型把明确数据类型的操作放到创建对象或者调用方法的时候再明确.                                J ...

  10. javax.xml.bind.UnmarshalException: 意外的元素 (uri:"", local:"xml")。所需元素为(none)

    将xml转换为object时候报错:javax.xml.bind.UnmarshalException: 意外的元素 (uri:"", local:"xml") ...