1. 功能与目的
就是下载一个网页的源代码,网址就是CSDN博客地址:
http://blog.csdn.net/woshisangsang2. 下载一个网页
通过urllib2模块的urlopen方法可以获取一个地址对应的html代码,注意在linux环境下,需要指明解释器的路径,并指明编码(不然没法使用中文)
#!/usr/bin/python2.7
# coding=UTF-8
import urllib2
#变量区域
url="http://blog.csdn.net/woshisangsang"#待下载的网址
#方法区域
def downloadWebsite(url):#下载
print("start to download:"+url)
try:
result=urllib2.urlopen(url).read()
except urllib2.URLError as ex:
print("download error,the reason is:"+ex.reason)
return result
result=downloadWebsite(url)
print(result)
运行结果如下(部分结果,证明程序跑成功了),通过这个结果我们可以想到href对应的链接就是一篇博文对应的地址。
<span class="link_title"><a href="/woshisangsang/article/details/77222166">
Java 线程与进程的速度比较(继承Thread实现)
</a>
</span>
3. 下载错误后重试下载
网页请求失败在所难免,所以可以重试下载,而对只有重试到最后一次仍然报错的显示错误信息。具体实现代码如下:
#!/usr/bin/python2.7
# coding=UTF-8
import urllib2
#变量区域
url="http://blog.csdn.net/woshisangsang11"#待下载的网址
#方法区域
def downloadWebsite(url,retry_time=5):
print("start to download:"+url+",the retry time is:"+str(retry_time))
try:
result=urllib2.urlopen(url).read()
except urllib2.URLError as ex:
if retry_time==1:
return "download error,the reason is:"+ex.reason+",error code"+str(ex.code)
else:
return downloadWebsite(url,retry_time-1)
return result
result=downloadWebsite(url)
print(result)
执行结果如下,可见咱这个程序是不服气的下载了5次,最后实在不行才报告错误的。最后error code是403,指的是可以连接该网站,但没有查看网页的权限,因为此处的url是我虚构的(加了11).
start to download:
http://blog.csdn.net/woshisangsang11,theretry time is:5
retry time is:4
retry time is:3
retry time is:2
retry time is:1
download error,the reason is:Forbidden,error code403
[Finished in 1.6s]