您的位置:首页 > 编程语言 > Python开发

Python项目实战之下载博客文章

2017-01-18 21:00 561 查看
1.打开博客列表首页
http://blog.sina.com.cn/s/articlelist_6053900192_0_1.html
目标:捕获所有文章的超链接

2. 博客文章列表特征

<a title=…   href=… .html>

3. 技术要点

字符串函数find

列表list[-x:-y]

文件读写操作

循环体while

4. 实现步骤

能够在浏览器里打开韩寒博客文章列表首页的博客网页

从首页网页里获得博客上的所有文章链接

所有文章列表网页里的文章链接

下载所有链接html文件、

5. python
#coding:utf-8

import urllib
import time
url=['']*350
page=1
link =1
while page <=7:
con=urllib.urlopen('http://blog.sina.com.cn/s/articlelist_1259295385_0_'+str(page)+'.html').read()
#print 'con', con
i=0
title=con.find(r'<a title=')
#print title
href=con.find(r'href=', title)
#print href
html=con.find(r'.html', href)
#print html
print url
while title != -1 and href != -1 and html != -1 and i < 350:
url[i]=con[href + 6:html + 5]
print link,' ',url[i]
title=con.find(r'<a title=', html)
href=con.find(r'href=', title)
html=con.find(r'.html', href)
i=i+1
link=link + 1
else:
print page, 'find end!'
page=page + 1
else:
print 'find end'

j=0
while j <350:
content=urllib.urlopen(url[j]).read()
open(r'xiongpan/'+url[j][-26:], 'w+').write(content)
print 'downloading', url[j]
j=j + 1
time.sleep(15)
else:
print 'download article finished'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python while find urllib