网络爬虫入门 (五) 初识scrapy框架

2018-07-19  本文已影响0人  闻榴莲的猫

一、简介

Scrapy,Python开发的一个快速,高层次的屏幕抓取和web抓取框架 ,用于抓取web站点并从页面中提取结构化的数据。Scrapy用途广泛,可 以用于数据挖掘、监测和自动化测试。
Scrapy吸引人的地方在于它是一个框架,任何人都可以根据需求方便 的修改。它也提供了多种类型爬虫的基类,如BaseSpider、sitemap爬虫 等,最新版本又提供了web2.0爬虫的支持。

二、Scrapy结构

1. 主要组件
2.基本流程

① 引擎从调度器中取出一个链接(URL)用于接下来的抓取
②引擎把URL封装成一个请求(Request)传给下载器
③下载器把资源下载下来,并封装成应答包(Response)
④爬虫解析Response
⑤解析出实体(Item),则交给实体管道进行进一步的处理
⑥解析出的是链接(URL),则把URL交给调度器等待抓

三、创建项目

使用anaconda安装:conda install scrapy
安装过程可能会比较慢,需耐心等待
在控制台输入指令scrapy startproject demoScrapy
即可在当前目录下创建Scrapy工程


工程目录

四、实战:爬取伯乐在线IT标签的所有文章的信息

1、分析
网址:http://blog.jobbole.com/category/it-tech/
2、在items文件的类中创建所需字段

    thumb_url = scrapy.Field()
    date = scrapy.Field()
    title = scrapy.Field()
    tag = scrapy.Field()
    summary = scrapy.Field()
    detail_url = scrapy.Field()

3、在spiders文件夹中创建一个scrapy.Spider的子类,并重写其中的name、start_urls、parse()

name = "list_spider"
start_urls = ["http://blog.jobbole.com/all-posts/"]
    def parse(self, response):
        result = dict()
        print("++++++"*50)
        container = response.xpath("//div[@class='post floated-thumb']")
        curr_page = int(response.xpath("//span[@class='page-numbers current']/text()").extract_first())
        # print(type(container))
        list_index = 1
        for item in container:
            # print(item)
            result["thumb_url"] = item.xpath("./div[@class='post-thumb']//img/@src").extract_first()
            content_container = item.xpath(".//div[@class='post-meta']")
            result["date"] = ""
            date_b = content_container.xpath("./p/text()").extract()
            match = re.findall("(\d{4}/\d{2}/\d{2})", str(date_b))
            if len(match):
                result["date"] = match[0]
            result["title"] = content_container.xpath("./p/a[@class='archive-title']/text()").extract_first()
            result["tag"] = content_container.xpath("./p/a[@rel]/text()").extract_first()
            result["summary"] = content_container.xpath("./span[@class='excerpt']/p/text()").extract_first()
            result["detail_url"] = content_container.xpath(".//span[@class='read-more']/a/@href").extract_first()
            result["curr_index"] = (curr_page-1) * 20 + list_index
            yield result
            list_index += 1
        next_page = response.xpath("//a[@class='next page-numbers']/@href").extract_first()
        if next_page:
            yield scrapy.Request(url=next_page, callback=self.parse)

提取标签信息用的是xpath,可以参考http://www.w3school.com.cn/xpath/index.asp
4、这时候所有数据都已经爬取到了,scrapy会将爬取到的数据输出到控制台

爬取到的数据
将数据存到数据库:
image.png
存到csv:
image.png

存到Excel:


image.png

项目地址:https://github.com/wsty/scrapy-list

上一篇 下一篇

猜你喜欢

热点阅读