Python标准库urllib

urllib是python的一个获取url的模块。它用urlopen函数的形式提供了一个非常简洁的接口。这使得用各种各样的协议获取url成为可能。它同时 也提供了一个稍微复杂的接口来处理常见的状况-如基本的认证,cookies,代理,等等。这些都是由叫做opener和handler的对象来处理的。


urllib


 

import urllib
s = urllib.urlopen('http://tieba.baidu.com/p/3606519228')
print s.read()  #将会打印出整个文件的html源代码

s.readline() #打印Html代码的第一行
s.getcode()  #返回Http状态码。如果是http请求,200请求成功完成;404网址未找到
s.info()     #返回一个httplib.HTTPMessage对象,表示远程服务器返回的头信息
s.geturl()   #返回请求的url 

>>> s = urllib.urlopen('http://www.alwme.com/')
>>> byte = s.read()
>>> print("从 %s 上获取了 %s 字节") % (s.geturl(),len(byte))
从 http://alwme.com/ 上获取了 26834 字节



urlget()  获取旧网址重定向后的网址,有时候我们常常访问一个网址会跳转到另一个网址,比如360百万美金买的网址www.so.com会跳转到新品牌网址www.haosou.com

from urllib2 import Request, urlopen

s = 'http://www.me.com/'
req = Request(s)
response = urlopen(req)

print 'old url is: ' + s 
print 'The redirect url is: ' + response.geturl(
运行结果:



info()     这个返回对象的字典对象,该字典描述了获取的页面情况。通常是服务器发送的特定头headers。目前是httplib.HTTPMessage 实例。包含"Content-length","Content-type",和其他内容

 print  urlopen('http://www.so.com').info()
运行结果:




urlretrieve() 返回一个二元组  urlretrieve将url定位到的html文件下载到你本地的硬盘中,如果不指定filename,则会存为临时文件。

临时存放:

>>> filename = urllib.urlretrieve('http://www.alwme.com/')
>>> type(filename)
<type 'tuple'>
>>> print filename
('/tmp/tmpaOdE2g', <httplib.HTTPMessage instance at 0x7f1b021e8680>)


 

存为本地文件:

>>> filename = urllib.urlretrieve('http://www.alwme.com/',filename='/home/zhg/temptest/alwme.html')
>>> type(filename)
<type 'tuple'>
>>> print filename
('/home/zhg/temptest/alwme.html', <httplib.HTTPMessage instance at 0x7f1b021e8a28>)

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值