1. 网页操作

urllib.urlopen(url[,data[,proxies]])

打开一个url,返回一个文件对象,然后可以进行类似文件对象操作

url:远程数据的路径,即网址

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

urlopen返回对象提供方法:

read() , readline() ,readlines() , fileno() , close() :这些方法的使用方式与文件对象完全一样

info():返回一个httplib.HTTPMessage对象,表示远程服务器返回的头信息

getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到

geturl():返回请求的url

 >>> import urllib
>>> resp = urllib.urlopen("http://www.google.com")
>>> read = resp.read() ######读取整个文件
>>> print read
............此处打印整个页面代码,略之.............
>>> readline = resp.readline() ######读取一行
>>> print readline
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" 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 http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 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

2. 下载

urllib.urlretrieve(url[,filename[,reporthook[,data]]])

urlretrieve方法将url定位到的html文件下载到你本地的硬盘中。如果不指定filename,则会存为临时文件

urlretrieve()返回一个二元组(filename,mine_hdrs),filename表示保存到本地的路径,mine_hdrs返回一个httplib.HTTPMessage实例,表示服务器的响应头

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

 >>> filename = urllib.urlretrieve('http://www.google.com.hk/')
>>> type(filename)
<type 'tuple'>
>>> filename[0]
'/tmp/tmp8eVLjq'
>>> filename[1]
<httplib.HTTPMessage instance at 0xb6a363ec>

临时存放

 >>> filename = urllib.urlretrieve('http://www.google.com.hk/',filename='/home/dzhwen/python文件/Homework/urllib/google.html')
>>> type(filename)
<type 'tuple'>
>>> filename[0]
'/home/dzhwen/python\xe6\x96\x87\xe4\xbb\xb6/Homework/urllib/google.html'
>>> filename[1]
<httplib.HTTPMessage instance at 0xb6e2c38c>

保存为本地

 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 = 'http://www.sina.com.cn'
local = '/py/sina.html'
urllib.urlretrieve(url, local, cbk)

下载进度实例

urllib.urlcleanup()

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

3. 编码与解码

urllib.quote(url)和urllib.quote_plus(url)

将url数据获取之后,并将其编码,从而适用与URL字符串中,使其能被打印和被web服务器接受

 >>> urllib.quote('http://www.baidu.com')
'http%3A//www.baidu.com'
>>> urllib.quote_plus('http://www.baidu.com')
'http%3A%2F%2Fwww.baidu.com'
urllib.unquote(url)和urllib.unquote_plus(url)

与urllib.quote(url)和urllib.quote_plus(url)函数相反

urllib.urlencode(query)

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

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

 >>> import urllib
>>> params=urllib.urlencode({'spam':1,'eggs':2,'bacon':0})
>>> params
'eggs=2&bacon=0&spam=1'
>>> f=urllib.urlopen("http://python.org/query?%s" % params)
>>> print f.read()

GET方法

 >>> import urllib
>>> parmas = urllib.urlencode({'spam':1,'eggs':2,'bacon':0})
>>> f=urllib.urlopen("http://python.org/query",parmas)
>>> f.read()

POST方法

补充:

quote(s, safe='/')

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

pathname2url(pathname)

将本地路径转换为url路经

url2pathname(pathname)

将url路经转换为本地路径

python模块—urllib的更多相关文章

  1. 【Python】Python的urllib模、urllib2模块的网络下载文件

    因为需要从一些下载一个页PDF文件.但是需要下载PDF有数百个文件,这是不可能用人工点击下载.只是Python有相关模块,所以写一个程序PDF文件下载,顺便熟悉Python的urllib模块和ulrl ...

  2. 定义一个方法get_page(url),url参数是需要获取网页内容的网址,返回网页的内容。提示(可以了解python的urllib模块)

    定义一个方法get_page(url),url参数是需要获取网页内容的网址,返回网页的内容.提示(可以了解python的urllib模块) import urllib.request def get_ ...

  3. Python 网络请求模块 urllib 、requests

    Python 给人的印象是抓取网页非常方便,提供这种生产力的,主要依靠的就是 urllib.requests这两个模块. urlib 介绍 urllib.request 提供了一个 urlopen 函 ...

  4. Python模块学习 --- urllib

    urllib模块提供的上层接口,使我们可以像读取本地文件一样读取www和ftp上的数据.每当使用这个模块的时候,老是会想起公司产品的客户端,同事用C++下载Web上的图片,那种“痛苦”的表情.我以前翻 ...

  5. Python的urllib和urllib2模块

    Python的urllib和urllib2模块都做与请求URL相关的操作,但他们提供不同的功能.他们两个最显着的差异如下: urllib2可以接受一个Request对象,并以此可以来设置一个URL的h ...

  6. python爬虫 urllib模块url编码处理

    案例:爬取使用搜狗根据指定词条搜索到的页面数据(例如爬取词条为‘周杰伦'的页面数据) import urllib.request # 1.指定url url = 'https://www.sogou. ...

  7. python 爬虫 urllib模块 目录

    python 爬虫 urllib模块介绍 python 爬虫 urllib模块 url编码处理 python 爬虫 urllib模块 反爬虫机制UA python 爬虫 urllib模块 发起post ...

  8. python模块使用案例

    python模块使用案例 一.使用MySQLdb模块代码示例: # 导入 MySQLdb模块 import MySQLdb # 和服务器建立链接,host是服务器ip,我的MySQL数据库搭建在本机, ...

  9. python中urllib, urllib2,urllib3, httplib,httplib2, request的区别

    permike原文python中urllib, urllib2,urllib3, httplib,httplib2, request的区别 若只使用python3.X, 下面可以不看了, 记住有个ur ...

随机推荐

  1. Unicode解码、URL编码/解码

    + (NSString *) stringByReplaceUnicode:(NSString *)string { NSMutableString *convertedString = [strin ...

  2. 前端开发的常用js库

    验证: jQuery formValidator,Validform; 提示框: artDialog, lhgDialog,jBox,jQuery textbox plugin 文件批量上传:uplo ...

  3. Mongodb集群搭建

    搭建高可用Mongodb集群 http://www.lanceyan.com/category/tech/mongodb/page/2 再看MongoDB副本集  http://blog.itpub. ...

  4. DIR和dirent结构体

    DIR结构体类似于FILE,是一个内部结构 struct __dirstream { void *__fd; char *__data; int __entry_data; char *__ptr; ...

  5. Repeater控件实现数据绑定,并实现分页效果

    前台显示代码 <pre name="code" class="csharp"><asp:Repeater ID="Repeater1 ...

  6. Android显示YUV图像

    需要流畅显示YUV图像需要使用Opengl库调用GPU资源,网上在这部分的资料很少.实际上Android已经为我们提供了相关的Opengl方法 主体过程如下: 1.建立GLSurfaceView 2. ...

  7. C语言 —— 括号配对问题(不使用栈)

    最近在南阳理工的OJ上刷题,看到一个有点意思的题目 网上的答案大多都使用了栈,可惜我还没有学习数据结构,所以只能用简单的方法来解决 题目的链接在这 http://acm.nyist.net/Judge ...

  8. webservice axis2客户端设置代理方法(公司网络通过代理访问时)

    webservice axis2客户端设置代理方法(公司网络通过代理访问时)   UploadProcessInServiceStub stub = new UploadProcessInServic ...

  9. 浅析C++内存分配与释放操作过程——三种方式可以分配内存new operator, operator new,placement new

    引言:C++中总共有三种方式可以分配内存,new operator, operator new,placement new. 一,new operator 这就是我们最常使用的 new 操作符.查看汇 ...

  10. 用gdb调试程序笔记: 以段错误(Segmental fault)为例

    用gdb调试程序笔记: 以段错误(Segmental fault)为例[转] 1.背景介绍2.程序中常见的bug分类3.程序调试器(如gdb)有什么用4.段错误(Segmental fault)介绍5 ...