Python爬虫爬取一篇韩寒新浪博客

时间:2023-03-09 04:28:54
Python爬虫爬取一篇韩寒新浪博客

网上看到大神对Python爬虫爬到非常多实用的信息,认为非常厉害。突然对想学Python爬虫,尽管自己没学过Python。但在网上找了一些资料看了一下,看到爬取韩寒新浪博客的视频。共三集,第一节讲爬取一篇博客,第二节讲爬取一页博客。第三集讲爬取所有博客。

看了视频。也留下了代码。

爬虫第一步:查看网页源码:

Python爬虫爬取一篇韩寒新浪博客

第一篇博客的代码为蓝底的部分<a title="" target="_blank" href="http://blog.sina.com.cn/s/blog_4701280b0102eo83.html">《论电影的七个元素》——关于我对电…</a>

对照其它博客的代码,找出公共部分“< title=‘’ ‘href=’,'.html'

代码为:

# -*- coding : -utf-8 -*-
import urllib
str0 ='<a title="" target="_blank" href="http://blog.sina.com.cn/s/blog_4701280b0102eo83.html">《论电影的七个元素》——关于我对电…</a>'
title = str0.find(r'<a title')
#print title
href = str0.find(r'href=')
#print href
html = str0.find(r'.html')
#print html url = str0[href + 6:html + 5]
print url content = urllib.urlopen(url).read()
#print content filename = url[-26:]
print filename
open(filename+'.html','w').write(content)
print '下载成功!'

执行结果:

Python爬虫爬取一篇韩寒新浪博客

保存的文件:

Python爬虫爬取一篇韩寒新浪博客