用Eclipse+Pydev作为开发环境,通过python3的urllib.request
爬取韩寒新浪博客所有文章链接
分析韩寒博客页面
审查元素查看文章链接
这就是我们要的东西(类似如下))
1
| <a title="" target="_blank" href="http://blog.sina.com.cn/s/blog_4701280b0102eksm.html">2013年09月06日</a>
|
由于要爬取多页还要分析页与页之间的联系
1 2 3 4 5
| 第一页:http://blog.sina.com.cn/s/articlelist_1191258123_0_1.html 第二页:http://blog.sina.com.cn/s/articlelist_1191258123_0_2.html 第三页:http://blog.sina.com.cn/s/articlelist_1191258123_0_3.html ... 第七页:http://blog.sina.com.cn/s/articlelist_1191258123_0_72.html
|
这也就发现了规律,只需要一个循环加字符串连接就可以解决
代码的实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import urllib.request url=['']*350 page=1 link=1 i=0 while page<=7: con=urllib.request.urlopen('http://blog.sina.com.cn/s/articlelist_1191258123_0_'+str(page)+'.html').read() con=con.decode() title=con.find(r'<a title') href=con.find(r'href=',title) html=con.find(r'.html',href) 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('all find end') j=0 link=1 while j<350 and url[j]!='': content=urllib.request.urlopen(url[j]).read() f=open(r'hanhan/'+url[j][-26:],'wb') f.write(content) print('downloading',link,' ',url[j]) j=j+1 link=link+1 f.close() else: print('download article finished')
|
代码运行
可自由转载、引用,但需署名作者且注明文章出处。