版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/WhoisPo/article/details/51064309
这个功能需要用到urlretrieve,这个函数在urllib.request包里面。如果有同学用的是python2,那么这个函数就在urllib里面。
关于urlretrieve这个函数的用法,http://www.nowamagic.net/academy/detail/1302861中给出了很好的说明,大家有兴趣可以看一看。
我的是另一个例子,出自《python核心编程》一书,原书是基于python2的版本
下载一个网页,然后显示第一和最后一非空行,代码如下
from urllib.request import urlretrieve
def firstNonBlank(lines):
for eachLine in lines:
if not eachLine.strip():
continue
else:
return eachLine
def firstLast(webpage):
f = open(webpage, 'r')
lines = f.readlines()
f.close()
print(firstNonBlank(lines))
lines.reverse()
print(firstNonBlank(lines))
def download(url="http://info.tsinghua.edu.cn", process=firstLast):
try:
retval = urlretrieve(url)[0]
except IOError:
retval = None
if retval:
print(retval)
process(retval)
if __name__ == '__main__':
download()