本文共 1518 字,大约阅读时间需要 5 分钟。
下午事情少,顺便把昨天的爬虫练习下,平时都看磊的技术博哥(干货比较多);就试试先写一个简单的爬虫,后期有机会再完善,做整站和多线程。
1、观察爬取的URL:
通过观察我们发现,在首页部分包含有文章的标题列表,然后思路就是;通过这一页的url可以获取所有文章标题,再通过标题获取到文章的URL,在通过RUL下载:
观察这一页的URL为:
http://dl528888.blog.51cto.com/2382721/p-1:第二页往后类推就是p-2..p-*,这样就很容易把整站都爬下来。
2、然后结合BeautifulSoup,分析结构,根据标题的内容往下爬取到连接,然后下载:
代码:
#coding:utf-8#author : xiaoluo#2015.10.10#http://dl528888.blog.51cto.com/2382721/p-1import urllib,urllib2from bs4 import BeautifulSoupclass Spider: def __init__(self,url): self.url = url self.headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6' } def binglogdict(self,url): result_dict = {} req = urllib2.Request(self.url,headers=self.headers) html = urllib2.urlopen(req) soup = BeautifulSoup(html) for i in soup.find_all("h3",attrs={"class":"artTitle"}): url = i.a.get("href") tal = i.get_text() result_dict[url]=tal return result_dict def downblog(self): result_dict = self.binglogdict(self.url+'/2382721/p-1') for k,v in result_dict.items(): url = self.url + k fname = v.strip('\n') + '.html' f = open(fname,'w+') req = urllib2.Request(url,headers=self.headers) html = urllib2.urlopen(req).read() f.write(html) f.close()if __name__ == '__main__': xiaoluo = Spider('http://dl528888.blog.51cto.com') xiaoluo.downblog()
运行结果、看到文章以标题的形式下载成了html文件,windows 下打开就是相应博客内容了:
转载地址:http://cstbl.baihongyu.com/