# -*-coding:utf-8-*-
# urllib用于访问不需要验证的网络资源
# urllib.urlretrave(url,tempfile, functionLodingProcess,[form_data])提供了下载资源的功能。所需参数如其名,
# 不给定临时文件时,自动生成,返回文件名,和执行信息。
# get 和post 是http的两种常用的方法,get-->就象明信片方式[内容显式放在URL中、内容长度受限、不安全]
# post-->信封模式[内容放在信封里,内容长度不受某些限制,安全]
# 实例get方式:
import urllib
import os
def reporthook(blocks_read, block_size, total_size):
"""total_size is reported in bytes;
block_size is the amount read each time;
block_read is the number of blocks successful read.
"""
if not blocks_read:
print 'connection opened'
return
if total_size
print 'read %d blocks,(%d bytes)' % (blocks_read, blocks_read * block_size)
else: # 给定了total_size值输出获得比值
amount_read = block_size * blocks_read
print 'read %d blocks, or %d/%d' % (blocks_read, amount_read, total_size)
return
try:
filename, msg = urllib.urlretrieve('http://cve.scap.org.cn/CVE-2015-4785.html', reporthook=reporthook)
finally:
print 'File Exist?:', os.path.exists(filename), filename
txt = file(filename)
content = txt.read()
print content
urllib.urlcleanup() # 清理临时文件
print 'File Exist?:', os.path.exists(filename)
1.urlopen()方法urllib.urlopen(url[, data[, proxies]]) :创建一个表示远程url的类文件对象,然后像本地文件一样操作这个类文件对象来获取远程数据。参数url表示远程数据的路径,一般是网址;参数data表示以post方式提交到url的数据(玩过web的人应该知道提交数据的两种方式:post与get。如果你不清楚,也不必太在意,一般情况下很少用到这个参数);参数proxies用于设置代理。urlopen返回 一个类文件对象,它提供了如下方法:read() , readline() , readlines() , fileno() , close() :这些方法的使用方式与文件对象完全一样;info():返回一个httplib.HTTPMessage 对象,表示远程服务器返回的头信息getcode():返回Http状态码。如果是http请求,200表示请求成功完成;404表示网址未找到;geturl():返回请求的url;
2.urlretrieve方法直接将远程数据下载到本地。
urllib.urlretrieve(url[, filename[, reporthook[, data]]])参数说明:url:外部或者本地urlfilename:指定了保存到本地的路径(如果未指定该参数,urllib会生成一个临时文件来保存数据);reporthook:是一个回调函数,当连接上服务器、以及相应的数据块传输完毕的时候会触发该回调。我们可以利用这个回调函数来显示当前的下载进度。data:指post到服务器的数据。该方法返回一个包含两个元素的元组(filename, headers),filename表示保存到本地的路径,header表示服务器的响应头。