刚接触Scrapy框架,不是很熟悉,之前用webdriver+selenium实现过头条的抓取,但是感觉对于整站抓取,之前的这种用无GUI的浏览器方式,效率不够高,所以尝试用CrawlSpider来实现。

这里通过一个实例加深对Scrapy框架的理解。

本文开发环境:

本文目标:抓取网站https://blog.scrapinghub.com的所有文章标题。

1.首页的布局分析

这个博客网站的页面结构如下图所示,我们的目标是抓取每页中间的item的标题,以及通过crawlspider自动抓取下一页的link链接达到自动抓取全站资源的目标。底部只有下一页的链接。

再来看第二页的布局:

中间的内容跟首页一样,只是在底部的分页导航,多了上一页(首页只有下一页)

所以,文章标题所在布局我们搞清楚了,分页导航的格式也十分简单:https://blog.scrapinghub.com/page/2,

只是最后一个数字不一样,这个数字就代表第几页文章。只是最后一个数字不一样,这个数字就代表第几页文章。

2.VSCode实现基于Scrapy框架的CrawlSpider爬虫

2.1 创建Scrapy工程

终端进入到D盘的tmp目录输入如下命令创建一个名字为blogscrapy的scrapy工程(官方文档:):

scrapy startproject blogscrapy

2.2 创建CrawlSpider爬虫

终端进入到 D:\tmp\blogscrapy,输入如下命令创建一个名为blogspider,允许爬虫的域名为scrapinghub.com的基于crawlSpider模板的spider爬虫(官方文档:):

scrapy genspider -t crawl blogspider blog.scrapinghub.com

2.3 定义item获取所需属性字段

items.py的内容如下:

# -*- coding: utf-8 -*-
import scrapy
class BlogscrapyItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()

2.3 修改spider定义抓取规则、存储字段

blog.py的内容如下:

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from blogscrapy.items import BlogscrapyItem class BlogSpider(CrawlSpider):
name = 'blog'
allowed_domains = ['blog.scrapinghub.com']
start_urls = ['http://blog.scrapinghub.com/'] rules = (
Rule(LinkExtractor(restrict_xpaths=('//div[@class="blog-pagination"]/a', )), callback='parse_item', follow=True),
) def parse_item(self, response):
for title in response.xpath('//div[@class="post-listing"]/div[@class="post-item"]/div[@class="post-header"]/h2'):
item = BlogscrapyItem()
item['title'] = title.xpath('./a/text()').extract_first()
yield item

pipeline.py的内容如下:

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import json class BlogscrapyPipeline(object): def __init__(self):
self.file = open('pipeline-result.json', 'a+', encoding='utf-8') def process_item(self, item, spider):
content = json.dumps(dict(item), ensure_ascii=False) + "\n"
self.file.write(content)
return item def close_spider(self, spider):
self.file.close()

最后,需要把pipeline的处理加到工程里面才能起作用,编辑工程目录下的settings.py文件,加入以下内容:

ITEM_PIPELINES = {
'blogscrapy.pipelines.BlogscrapyPipeline': 300,
}

3. 运行结果

上图看到成功爬取了12页内容,每页10条,总共115篇文章。

4. 本文源码下载

下载地址: 点我去下载


参考资料

[1]: Scrapy官方文档
[2]: Python3爬取今日头条系列

[3]: 廖雪峰老师的Python3 在线学习手册

[4]: Python3官方文档

[5]: 菜鸟学堂-Python3在线学习

[6]: XPath语法参考

Scrapy 使用CrawlSpider整站抓取文章内容实现的更多相关文章

  1. wget整站抓取、网站抓取功能;下载整个网站;下载网站到本地

    wget -r   -p -np -k -E  http://www.xxx.com 抓取整站 wget -l 1 -p -np -k       http://www.xxx.com 抓取第一级 - ...

  2. Scrapy爬虫入门系列4抓取豆瓣Top250电影数据

    豆瓣有些电影页面需要登录才能查看. 目录 [隐藏]  1 创建工程 2 定义Item 3 编写爬虫(Spider) 4 存储数据 5 配置文件 6 艺搜参考 创建工程 scrapy startproj ...

  3. Node.js 爬虫,自动化抓取文章标题和正文

    持续进行中... 目标: 动态User-Agent模拟浏览器 √ 支持Proxy设置,避免被服务器端拒绝 √ 支持多核模式,发挥多核CPU性能 √ 支持核内并发模式 √ 自动解码非英文站点,避免乱码出 ...

  4. 如何让搜索引擎抓取AJAX内容? 转

    越来越多的网站,开始采用"单页面结构"(Single-page application). 整个网站只有一张网页,采用 Ajax 技术,根据用户的输入,加载不同的内容. 这种做法的 ...

  5. 如何让搜索引擎抓取AJAX内容?

    越来越多的网站,开始采用"单页面结构"(Single-page application). 整个网站只有一张网页,采用Ajax技术,根据用户的输入,加载不同的内容. 这种做法的好处 ...

  6. Python抓取视频内容

    Python抓取视频内容 Python 是一种面向对象.解释型计算机程序设计语言,由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年.Python语法简洁而清晰,具 ...

  7. 【java】抓取页面内容,提取链接(此方法可以http get无需账号密码的请求)

    package 网络编程; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileOutpu ...

  8. 如何使用angularjs实现抓取页面内容

    <html ng-app="myApp"> <head> <title>angularjs-ajax</title> <scr ...

  9. 查询数据,从链接地址中爬取文章内容jsoup

    查询数据,从链接地址中爬取文章内容 protected void doGet(HttpServletRequest request, HttpServletResponse response) thr ...

随机推荐

  1. Oracle logminer 日志挖掘

    Table of Contents 1. LOGMNR简介 2. 创建数据字典 2.1. 外部文件存储数据字典 2.2. redo log 存储数据字典 3. 添加需要分析的文件 4. 开始分析文件 ...

  2. 关于springboot整合配置pagehelper插件的方法

    一,java代码配置法 这种方法个人感觉比较繁琐不是很推荐,而且也不怎么符合springboot的理念,但是胜在也能够用,所以就列起来,万一以后接手的代码是用这种方式的也方便自己维护. 首先引入jar ...

  3. .gz解压

    1.今天很神奇我遇到这样的压缩包,啧啧啧,好少见的,记录下 gzip  -d  http_log.gz 这是讲http_log文件解压到当前的路径下

  4. 集腋成裘-05-angularJS -初识angular

    私以为angular的最大特点是:只关注数据 1.1 angular之:双向绑定 <!DOCTYPE html> <html ng-app=""> < ...

  5. Cannot uninstall 'html5lib'. It is a distutils installed project and thus we cannot accurately determine which files belong to it which would lead to only a partial uninstall.

    如标题,安装Tensorflow-gpu时遇到的完整问题 Cannot uninstall 'html5lib'. It is a distutils installed project and th ...

  6. Python迷宫游戏(基础版)

    # 画地图map_data = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 1, 1, 1, 1, 1, 1, 1, 1], [1, 2, 1, 0, 0, 0, ...

  7. WPF应用程序内存泄漏的一些原因

    原文:Finding Memory Leaks in WPF-based applications There are numbers of blogs that folks wrote about ...

  8. 开始写博客,学习Linq

    除了为处理数据提供全新的方法之外,LINQ还代表了一种朝着声明式以及函数式编程发展的转变. 当人们问我为什么要学习LINQ时,我会告诉他们LINQ可以处理XML.关系型数据以及内存中的集合,更会提到L ...

  9. OSGi HelloWorld

    1.创建项目 2.Debug Configurations,配好之后,可以点一下右下角的Validate Bundles验证一下是否有问题 3.Debug

  10. Theorems for existence and uniqueness of variational problem

    Introduction Among simulation engineers, it is well accepted that the solution of a PDE can be envis ...