一. 网页操作
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():返回
-
>>> import urllib
-
>>> resp = urllib.urlopen(" style="color:#0000CC;">)
-
>>> read = resp.read() ######读取整个文件
-
>>> print read
-
............此处打印整个页面代码,略之.............
-
>>> readline = resp.readline() ######读取一行
-
>>> print readline
-
<!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}
-
>>> readlines = resp.readlines() ######逐行读取
>>> print readlines
.............................略之.................................
-
-
>>> fileno = resp.fileno() ######返回整数的底层实现使用请求从操作系统的I/O操作的文件描述符
-
>>> print fileno
-
3
-
>>> info = resp.info()
-
>>> print info
-
Date: Tue, 22 Sep 2015 08:36:58 GMT
-
Expires: -1
-
Cache-Control: private, max-age=0
-
Content-Type: text/html; charset=Big5
-
P3P: CP="This is not a P3P policy! See for more info."
-
Server: gws
-
X-XSS-Protection: 1; mode=block
-
X-Frame-Options: SAMEORIGIN
-
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
-
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
-
Accept-Ranges: none
-
Vary: Accept-Encoding
-
-
>>> statuscode = resp.getcode()
-
>>> print statuscode
-
200
-
>>> url = resp.geturl()
-
>>> print url
-
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到服务器的数据
-
root@wang-virtual-machine:/py# vim cbk.py
-
-
#coding=UTF-8
-
import urllib
-
-
def cbk(a,b,c):
-
'''回调函数
-
@a: 已经下载的数据块
-
@b: 数据块的大小
-
@c: 远程文件的大小
-
'''
-
per = 100.0 * a * b / c
-
if per > 100:
-
per = 100
-
print '%.2f%%' % per
-
url = ''
-
local = '/py/sina.html'
-
urllib.urlretrieve(url, local, cbk)
urlcleanup()
清除由于urllib.urlretrieve()所产生的缓存
三. 编码与解码
urlencode(query, doseq=0)
将URL中的键值对以连接符&划分
这里可以与urlopen结合以实现post方法和get方法:
-
>>> import urllib
-
>>> params = urllib.urlencode({'x':1,'y':2,'z':3})
-
>>> params
-
'y=2&x=1&z=3'
-
>>> url = urllib.urlopen("%s" % params)
-
>>> print url.geturl()
-
http://localhost/query?y=2&x=1&z=3
quote(s, safe='/')
对字符串进行编码,参数safe指定了不需要编码的字符,默认不编码字符/。
-
>>> urllib.quote(" aaa")
-
'http%3A//localhost/_cat%3F%20aaa'
-
>>> urllib.quote(" aaa",safe=":")
-
'http:%2F%2Flocalhost%2F_cat%3F%20aaa'
unquote(s)
对字符串进行解码
quote_plus(s, safe='')
对字符串进行编码,参数safe指定了不需要编码的字符
-
>>> urllib.quote_plus(" aaa")
-
'http%3A%2F%2Flocalhost%2F_cat%3F+aaa'
-
>>> urllib.quote_plus(" aaa",safe=":")
-
与quote()不同的是:quote()中是以%20替换' ',quote_plus()中是以+替换' '
-
>>> urllib.quote("aaa bbb")
-
'aaa%20bbb'
-
>>> urllib.quote_plus("aaa bbb")
-
'aaa+bbb'
unquote_plus(s)
对字符串进行解码
pathname2url(pathname)
将本地路径转换为url路经
url2pathname(pathname)
将url路经转换为本地路径
阅读(1753) | 评论(0) | 转发(0) |