前面讲到只是爬取了title和url,那么怎么爬取文章,其实原理是同样的。mongodb
咱们在item.py
中添加一项,以下:浏览器
class CsdnArticleItem(Item): title = Field() article = Field() pass
咱们保存文章的题目和内容。markdown
csdn是怎么来保存一篇文章的,咱们来看一个url:
http://blog.csdn.net/zhx6044/article/details/45698535
http://blog.csdn.net
是域名。
zhx6044是做者。
article/details
是固定的,那么只是最后的数字不一样,因此数字用来索引一篇文章。ide
在csdn_crawler.py
中的CsdnCrawlerSpider
的rules
中添加一个对于文章内容的爬取规则,以下:函数
rules = ( Rule(LinkExtractor(allow=r'article/list/[0-9]{1,20}'), callback='parse_item', follow=True), Rule(LinkExtractor(allow=r'article/details/[0-9]{1,20}'), callback='parse_article', follow=True), )
而后咱们实现一个其处理这个规则连接内容的回调函数。以下:url
def parse_article(self, response): i = CsdnArticleItem() i['title'] = response.xpath('//*[@id="article_details"]/div[1]/h1/span/a/text()').extract() i['article'] = response.xpath('//*[@id="article_content"]').extract() return i
使用的仍是Chromium浏览器的Copy XPath功能。
在提取文章内容时很差处理,为了实现更好的页面表现效果,其中实现比较复杂,我不能值爬取文字内容,因此如今只能连样式一块儿爬下来。
这样添加以后,咱们的爬虫就但是运行了。spa
这是其中的一些运行log:.net
2015-05-16 14:35:51+0800 [csdn_crawler] DEBUG: Filtered duplicate request: <GET http://blog.csdn.net/zhx6044/article/list/3> - no more duplicates will be shown (see DUPEFILTER_DEBUG to show all duplicates) 2015-05-16 14:35:57+0800 [csdn_crawler] DEBUG: Crawled (200) <GET http://blog.csdn.net/zhx6044/article/details/45649045> (referer: http://blog.csdn.net/zhx6044) 2015-05-16 14:35:57+0800 [csdn_crawler] DEBUG: Article add to mongodb database!
其能够看到其爬取了http://blog.csdn.net/zhx6044/article/details/45649045
这篇文章。
你们须要注意的是,这个爬虫虽然是从你的blog开始爬取,可是你的博客页面中还会包含其它人的连接,好比在推荐文章这一栏,如图:
code
这是你能够在添加爬取规则时添加上限制,好比:
Rule(LinkExtractor(allow=r'zhx6044/article/details/[0-9]{1,20}'), callback='parse_article', follow=True),
就能够了,否则你会发现你的爬虫根本停不下来。blog
这是我爬取到的数据,文章内容有点乱。