Chinaunix首页 | 论坛 | 博客
  • 博客访问: 18281
  • 博文数量: 2
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 25
  • 用 户 组: 普通用户
  • 注册时间: 2014-12-29 10:03
文章分类

全部博文(2)

文章存档

2015年(2)

我的朋友
最近访客

分类: Python/Ruby

2015-09-22 22:10:27

一. 网页操作

 urlopen(url, data=None, proxies=None)

 为指定的url创建一个类文件对象,然后像本地文件一样操作这个类文件对象来获取远程数据。
url:远程数据的路径,即网址

data:表示以GET或者POST方式请求url的数据
proxes:设置代理

urlopen返回一个类文件对象,它提供一下方法:

read(),readline(),readlines(),fileno(),close():这些方法的使用方式与文件对象完全一致
info():返回一个httplib.HTTPMessage实例,表示远程服务器返回的头信息
geturl():返回请求的url
getcode():返回

  1. >>> import urllib
  2. >>> resp = urllib.urlopen(" style="color:#0000CC;">)
  3. >>> read = resp.read()   ######读取整个文件
  4. >>> print read
  5. ............此处打印整个页面代码,略之.............
  6. >>> readline = resp.readline() ######读取一行
  7. >>> print readline
  8. <!doctype html><html itemscope="" itemtype=" lang="zh-HK"><head><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script>(function(){window.google={kEI:'KhMBVtO1KuGQmgWe2ILYDQ',kEXPI:'3700263,4014829,4024207,4027916,4029815,4031109,4032235,4032500,4032678,4033307,4033344,4034882,4036527,4037333,4037569,4037934,4038012,4041302,4041323,4041440,4041507,4041837,4042160,4042180,4043255,4043411,4043457,4043459,4043491,4043564,4044246,4044336,4044339,4044343,4044606,4044852,4044864,4045003,4045414,4045711,4045717,4045764,4045841,4045871,4046059,4046121,4046304,4046340,4046606,4046717,4047133,4047530,4047599,4047668,4047751,4048048,4048125,8300200,8300203,8501987,8501992,8502156,10200083',authuser:0,kscs:'c9c918f0_10'};google.kHL='zh-HK';})();(function(){google.lc=[];google.li=0;google.getEI=function(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||google.kEI};google.getLEI=function(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b};google.https=function(){return"https:"==window.location.protocol};google.ml=function(){return null};google.time=function(){return(new Date).getTime()};google.log=function(a,b,d,e,g){a=google.logUrl(a,b,d,e,g);if(""!=a){b=new Image;var c=google.lc,f=google.li;c[f]=b;b.onerror=b.onload=b.onabort=function(){delete c[f]};window.google&&window.google.vel&&window.google.vel.lu&&window.google.vel.lu(a);b.src=a;google.li=f+1}};google.logUrl=function(a,b,d,e,g){var c="",f=google.ls||"";if(!d&&-1==b.search("&ei=")){var h=google.getEI(e),c="&ei="+h;-1==b.search("&lei=")&&((e=google.getLEI(e))?c+="&lei="+e:h!=google.kEI&&(c+="&lei="+google.kEI))}a=d||"/"+(g||"gen_204")+"?atyp=i&ct="+a+"&cad="+b+c+f+"&zx="+google.time();/^http:/i.test(a)&&google.https()&&(google.ml(Error("a"),!1,{src:a,glmm:1}),a="");return a};google.y={};google.x=function(a,b){google.y[a.id]=[a,b];return!1};google.load=function(a,b,d){google.x({id:a+k++},function(){google.load(a,b,d)})};var k=0;})();var _gjwl=location;function _gjuc(){var a=_gjwl.href.indexOf("#");if(0<=a&&(a=_gjwl.href.substring(a),0<a.indexOf("&q=")||0<=a.indexOf("#q="))&&(a=a.substring(1),-1==a.indexOf("#"))){for(var d=0;d<a.length;){var b=d;"&"==a.charAt(b)&&++b;var c=a.indexOf("&",b);-1==c&&(c=a.length);b=a.substring(b,c);if(0==b.indexOf("fp="))a=a.substring(0,d)+a.substring(c,a.length),c=d;else if("cad=h"==b)return 0;d=c}_gjwl.href="/search?"+a+"&cad=h";return 1}return 0}

  9. >
    >> readlines = resp.readlines() ######逐行读取
    >
    >> print readlines

    .............................略之.................................

  10. >>> fileno = resp.fileno()  ######返回整数的底层实现使用请求从操作系统的I/O操作的文件描述符
  11. >>> print fileno
  12. 3
  13. >>> info = resp.info()
  14. >>> print info
  15. Date: Tue, 22 Sep 2015 08:36:58 GMT
  16. Expires: -1
  17. Cache-Control: private, max-age=0
  18. Content-Type: text/html; charset=Big5
  19. P3P: CP="This is not a P3P policy! See for more info."
  20. Server: gws
  21. X-XSS-Protection: 1; mode=block
  22. X-Frame-Options: SAMEORIGIN
  23. Set-Cookie: PREF=ID=1111111111111111:FF=0:NW=1:TM=1442911018:LM=1442911018:V=1:S=mEKtFlZwAwUmso5J; expires=Thu, 31-Dec-2015 16:02:17 GMT; path=/; domain=.google.com.hk
  24. Set-Cookie: NID=71=CqIYFwoA4vkAAu_Zu8X_IEElnFUbjPTO-BHG1zq9MjE6GQZbQX7ZArRNmDPL0p0cmSBu3GEX_H4S_DqGfFSYUzSWzlQhKGp16nNK2kP25iJwWrCxmxdJ_2xbFvwhhkSxQrdC5g; expires=Wed, 23-Mar-2016 08:36:58 GMT; path=/; domain=.google.com.hk; HttpOnly
  25. Accept-Ranges: none
  26. Vary: Accept-Encoding

  27. >>> statuscode = resp.getcode()
  28. >>> print statuscode
  29. 200
  30. >>> url = resp.geturl()
  31. >>> print url
  32. http://www.google.com.hk/?gws_rd=cr

二. 下载

 urlretrieve(url, filename=None, reporthook=None, data=None)

urlretrieve方法将url定位到的html文件下载到你本地的硬盘中。如果不指定filename,则会存为临时文件。
该方法返回一个包含两个元素的元组
(filename, headers)filename表示保存到本地的路径,header返回一个httplib.HTTPMessage实例,表示服务器的响应头。

filename:指定了保存到本地的路径(如果未指定该参数,urllib会生成一个临时文件来保存数据)
reporthook:是一个回调函数,当连接上服务器、以及相应的数据块传输完毕的时候会触发该回调。我们可以利用这个回调函 数来显示当前的下载进度
data:指POST或者GET到服务器的数据

  1. root@wang-virtual-machine:/py# vim cbk.py

  2. #coding=UTF-8
  3. import urllib

  4. def cbk(a,b,c):
  5.     '''回调函数
  6.     @a: 已经下载的数据块
  7.     @b: 数据块的大小
  8.     @c: 远程文件的大小
  9.     '''
  10.     per = 100.0 * a * b / c
  11.     if per > 100:
  12.         per = 100
  13.     print '%.2f%%' % per
  14. url = ''
  15. local = '/py/sina.html'
  16. urllib.urlretrieve(url, local, cbk)

 urlcleanup()

清除由于urllib.urlretrieve()所产生的缓存

三. 编码与解码

 urlencode(query, doseq=0)

将URL中的键值对以连接符&划分

这里可以与urlopen结合以实现post方法和get方法:

  1. >>> import urllib
  2. >>> params = urllib.urlencode({'x':1,'y':2,'z':3})
  3. >>> params
  4. 'y=2&x=1&z=3'
  5. >>> url = urllib.urlopen("%s" % params)
  6. >>> print url.geturl()
  7. http://localhost/query?y=2&x=1&z=3

 quote(s, safe='/')

对字符串进行编码,参数safe指定了不需要编码的字符,默认不编码字符/。

  1. >>> urllib.quote(" aaa")
  2. 'http%3A//localhost/_cat%3F%20aaa'
  3. >>> urllib.quote(" aaa",safe=":")
  4. 'http:%2F%2Flocalhost%2F_cat%3F%20aaa'

 unquote(s)

对字符串进行解码

 quote_plus(s, safe='')

对字符串进行编码,参数safe指定了不需要编码的字符

  1. >>> urllib.quote_plus(" aaa")
  2. 'http%3A%2F%2Flocalhost%2F_cat%3F+aaa'
  3. >>> urllib.quote_plus(" aaa",safe=":")

与quote()不同的是:quote()中是以%20替换' ',quote_plus()中是以+替换' '
  1. >>> urllib.quote("aaa bbb")
  2. 'aaa%20bbb'
  3. >>> urllib.quote_plus("aaa bbb")
  4. 'aaa+bbb'

 unquote_plus(s)

对字符串进行解码

 pathname2url(pathname)

将本地路径转换为url路经

 url2pathname(pathname)

将url路经转换为本地路径

阅读(1742) | 评论(0) | 转发(0) |
0

上一篇:linux中时间设置date、hwclock、clock

下一篇:没有了

给主人留下些什么吧!~~