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()所产生的缓存