Python学习之urlib模块和urllib2模块学习

2014-11-23 22:06:54 · 作者: · 浏览: 13

一 urlib模块


利用urllib模块可以打开任意个url。
1.
urlopen() 打开一个url返回一个文件对象,可以进行类似文件对象的操作。


In [308]: import urllib



In [309]: file=urllib.urlopen('


In [310]: file.readline()


Out[310]: '\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8</p><br/><p><br />可以用read(),readlines(),fileno(),close()这些函数</p><br/><p>In [337]: file.info()</p><br/><p>Out[337]: <httplib.HTTPMessage instance at 0x2394a70></p><br/><p> </p><br/><p>In [338]: file.getcode()</p><br/><p>Out[338]: 200</p><br/><p> </p><br/><p>In [339]: file.geturl()</p><br/><p>Out[339]: 'http://www.baidu.com/'</p><br/><p>2.urlretrieve() 将url对应的html页面保存为文件</p><br/><p>In [404]: filename=urllib.urlretrieve('http://www.baidu.com/',filename='/tmp/baidu.html')</p><br/><p>In [405]: type (filename)</p><br/><p>Out[405]: <type 'tuple'></p><br/><p> </p><br/><p>In [406]: filename[0]</p><br/><p>Out[406]: '/tmp/baidu.html'</p><br/><p> </p><br/><p>In [407]: filename</p><br/><p>Out[407]: ('/tmp/baidu.html', <httplib.HTTPMessage instance at 0x23ba878>)</p><br/><p> </p><br/><p>In [408]: filename[1]</p><br/><p>Out[408]: <httplib.HTTPMessage instance at 0x23ba878></p><br/><p><br />3.urlcleanup() 清除由urlretrieve()产生的缓存</p><br/><p>In [454]: filename=urllib.urlretrieve('http://www.baidu.com/',filename='/tmp/baidu.html')</p><br/><p>In [455]: urllib.urlcleanup()</p><br/><p>4.urllib.quote()和urllib.quote_plus() 将url进行编码</p><br/><p>In [483]: urllib.quote('http://www.baidu.com')</p><br/><p>Out[483]: 'http%3A//www.baidu.com'</p><br/><p> </p><br/><p>In [484]: urllib.quote_plus('http://www.baidu.com')</p><br/><p>Out[484]: 'http%3A%2F%2Fwww.baidu.com'</p><br/><p><br />5.urllib.unquote()和urllib.unquote_plus() 将编码后的url解码</p><br/><p>In [514]: urllib.unquote('http%3A//www.baidu.com')</p><br/><p>Out[514]: 'http://www.baidu.com'</p><br/><p> </p><br/><p>In [515]: urllib.unquote_plus('http%3A%2F%2Fwww.baidu.com')</p><br/><p>Out[515]: 'http://www.baidu.com'</p><br/><p><br />6.urllib.urlencode() 将url中的键值对以&划分,可以结合urlopen()实现POST方法和GET方法</p><br/><p>In [560]: import urllib</p><br/><p>In [561]: params=urllib.urlencode({'spam':1,'eggs':2,'bacon':0})</p><br/><p>In [562]: f=urllib.urlopen("http://python.org/query %s" %params)</p><br/><p>In [563]: f.readline()</p><br/><p>Out[563]: '<!doctype html>\n'</p><br/><p> </p><br/><p>In [564]: f.readlines()</p><br/><p>Out[564]:</p><br/><p>['<!--[if lt IE 7]> <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9"> <![endif]-->\n',</p><br/><p> '<!--[if IE 7]> <html class="no-js ie7 lt-ie8 lt-ie9"> <![endif]-->\n',</p><br/><p> '<!--[if IE 8]> <html class="no-js ie8 lt-ie9"> <![endif]-->\n',</p><br/><p> '<!--[if gt IE 8]><!--><html class="no-js" lang="en" dir="ltr"> <!--<![endif]-->\n',</p><br/><p> '\n',</p><br/><p>二 urllib2模块</p><br/><p>urllib2比urllib多了些功能,例如提供基本的认证,重定向,cookie等功能</p><br/><p>https://docs.python.org/2/library/urllib2.html</p><br/><p>https://docs.python.org/2/howto/urllib2.html</p><br/><p>In [566]: import urllib2</p><br/><p> </p><br/><p>In [567]: f=urllib2.urlopen('http://www.python.org/')</p><br/><p> </p><br/><p>In [568]: print f.read(100)</p><br/><p>--------> print(f.read(100))</p><br/><p><!doctype html></p><br/><p><!--[if lt IE 7]> <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9"> <![endif]--></p><br/><p><br />打开python的官网并返回头100个字节内容</p><br/><p>HTTP基于请求和响应,客户端发送请求,服务器响应请求。urllib2使用一个Request对象代表发送的请求,调用urlopen()打开Request对象可以返回一个response对象。reponse对象是一个类似文件的对象,可以像文件一样进行操作</p><br/><p>In [630]: import urllib2</p><br/><p> </p><br/><p>In [631]: req=urllib2.Request('http://www.baidu.com')</p><br/><p> </p><br/><p>In [632]: response=urllib2.urlopen(req)</p><br/><p> </p><br/><p>In [633]: the_page=response.read()</p><br/><p> </p><br/><p>In [634]: the_page</p><br/><p>Out[634]: '<!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.</p><br/><p>通常情况下需要向一个url以POST的方式发送数据。</p><br/><p>In [763]: import urllib</p><br/><p> </p><br/><p>In [764]: import urllib2</p><br/><p> </p><br/><p>In [765]: url='http://xxxxxx/login.php'</p><div class="article-middle-ad" style="margin: 30px 0; padding: 20px 0; text-align: center; clear: both;"> <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-3873923678443673" crossorigin="anonymous"></script> <!-- cppentry文章内广告 --> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-3873923678443673" data-ad-slot="5723320063" data-ad-format="auto" data-full-width-responsive="true"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div><br/><p> </p><br/><p>In [766]: values={'ver' : '1.7.1', 'email' : 'xxxxx', 'password' : 'xxxx', 'mac' : '111111111111'}</p><br/><p> </p><br/><p>In [767]: data=urllib.urlencode(values)</p><br/><p> </p><br/><p>In [768]: req=urllib2.Request(url,data)</p><br/><p> </p><br/><p>In [769]: response=urllib2.urlopen(req)</p><br/><p> </p><br/><p>In [770]: the_page=response.read()</p><br/><p> </p><br/><p>In [771]: the_page</p><br/><p>如果不使用urllib2.Request()发送data参数,urllib2使用GET请求,GET请求和POST请求差别在于POST请求常有副作用,POST请求会通过某些方式改变系统的状态。也可以通过GET请求发送数据。</p><br/><p>In [55]: import urllib2</p><br/><p> </p><br/><p>In [56]: import urllib</p><br/><p> </p><br/><p>In [57]: url='http://xxx/login.php'</p><br/><p> </p><br/><p>In [58]: values={'ver' : 'xxx', 'email' : 'xxx', 'password' : 'xxx', 'mac' : 'xxx'}</p><br/><p> </p><br/><p>In [59]: data=urllib.urlencode(values)</p><br/><p> </p><br/><p>In [60]: full_url=url + ' ' + data</p><br/><p> </p><br/><p>In [61]: the_page=urllib2.urlopen(full_url)</p><br/><p> </p><br/><p>In [63]: the_page.read()</p><br/><p>Out[63]: '{"result":0,"data":0}'</p><br/><p> </p><br/><p>默认情况下,urllib2使用Python-urllib/2.6 表明浏览器类型,可以通过增加User-Agent HTTP头</p><br/><p>In [107]: import urllib</p><br/><p> </p><br/><p>In [108]: import urllib2</p><br/><p> </p><br/><p>In [109]: url='http://xxx/login.php'</p><br/><p> </p><br/><p>In [110]: user_agent='Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'</p><br/><p> </p><br/><p>In [111]: values={'ver' : 'xxx', 'email' : 'xxx', 'password' : 'xxx', 'mac' : 'xxxx'}</p><br/><p> </p><br/><p>In [112]: headers={'User-Agent' : user_agent}</p><br/><p> </p><br/><p>In [114]: data=urllib.urlencode(values)</p><br/><p> </p><br/><p>In [115]: req=urllib2.Request(url,data,headers)</p><br/><p> </p><br/><p>In [116]: response=urllib2.urlopen(req)</p><br/><p> </p><br/><p>In [117]: the_page=response.read()</p><br/><p> </p><br/><p>In [118]: the_page</p><br/><p>当给定的url不能连接时,urlopen()将报URLError异常,当给定的url内容不能访问时,urlopen()会报HTTPError异常</p><br/><p>#/usr/bin/python</p><br/><p> </p><br/><p>from urllib2 import Request,urlopen,URLError,HTTPError</p><br/><p>req=Request('http://10.10.41.42/index.html')</p><br/><p>try:</p><br/><p> response=urlopen(req)</p><br/><p>except HTTPError as e:</p><br/><p> print 'The server couldn\'t fulfill the request.'</p><br/><p> print 'Error code:',e.code</p><br/><p> </p><br/><p>except URLError as e:</p><br/><p> print 'We failed to fetch a server.'</p><br/><p> print 'Reason:',e.reason</p><br/><p>else:</p><br/><p> print "Everything is fine"</p><br/><p>这里需要注意的是在写异常处理时,HTTPError必须要写在URLError前面</p><br/><p>#/usr/bin/python</p><br/><p> </p><br/><p>from urllib2 import Request,urlopen,URLError,HTTPError</p><br/><p>req=Request('http://10.10.41.42')</p><br/><p>try:</p><br/><p> response=urlopen(req)</p><br/><p> </p><br/><p>except URLError as e:</p><br/><p> if hasattr(e,'reason'):</p><br/><p> print 'We failed to fetch a server.'</p><br/><p> print 'Reason:',e.reason</p><br/><p> elif hasattr(e,'code'):</p><br/><p> print 'The server couldn\'t fulfill the request.'</p><br/><p> print 'Error code:',e.code</p><br/><p>else:</p><br/><p> print "Everything is fine"</p><br/><p>hasattr()函数判断一个对象是否有给定的属性</p><br/></span> </div> <div class="pagination mt-40"> </div> <div class="article-footer mt-60 pt-40"> <div class="share-box"> <!-- Baidu Share Code Simplified or Removed if not needed. Keeping basic structure --> <div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more"></a><a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a><a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a><a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博"></a><a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网"></a><a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a></div> <script>window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"24"},"share":{}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];</script> </div> <div class="prev-next mt-20"> <div class="prev"> <span class="label">上一篇</span> <a href="bencandy.php?fid=54&id=21953" onclick="" class="link">Python学习之socket模块</a> </div> <div class="next"> <span class="label">下一篇</span> <a href="bencandy.php?fid=54&id=21951" onclick="" class="link">shell脚本中的“2< " ">&..</a> </div> </div> </div> </div> </div> </div> </div><!-- End .container.main-content --> <footer class="container mt-20 site-footer"> <div id="copyright"> Copyright © https://www.cppentry.com all rights reserved <a href="http://www.miibeian.gov.cn" target="_blank">粤ICP备13067022号-3</a><br> </div> </footer> <script> // Logic for double click admin editing </script> <script> if(typeof clickEdit !== 'undefined') clickEdit.init(); </script> </body> </html>