基于 Python 的 Scrapy 爬虫入门:页面提取

目录


下面建立一个爬虫项目,以图虫网为例抓取图片。python

1、内容分析

打开 图虫网,顶部菜单“发现” “标签”里面是对各类图片的分类,点击一个标签,好比“美女”,网页的连接为:https://tuchong.com/tags/美女/,咱们以此做为爬虫入口,分析一下该页面:web

打开页面后出现一个个的图集,点击图集可全屏浏览图片,向下滚动页面会出现更多的图集,没有页码翻页的设置。Chrome右键“检查元素”打开开发者工具,检查页面源码,内容部分以下:数据库

<div class="content">
    <div class="widget-gallery">
        <ul class="pagelist-wrapper">
            <li class="gallery-item...

能够判断每个li.gallery-item是一个图集的入口,存放在ul.pagelist-wrapper下,div.widget-gallery是一个容器,若是使用 xpath 选取应该是://div[@class="widget-gallery"]/ul/li,按照通常页面的逻辑,在li.gallery-item下面找到对应的连接地址,再往下深刻一层页面抓取图片。json

可是若是用相似 Postman 的HTTP调试工具请求该页面,获得的内容是:segmentfault

<div class="content">
    <div class="widget-gallery"></div>
</div>

也就是并无实际的图集内容,所以能够判定页面使用了Ajax请求,只有在浏览器载入页面时才会请求图集内容并加入div.widget-gallery中,经过开发者工具查看XHR请求地址为:数组

https://tuchong.com/rest/tags/美女/posts?page=1&count=20&order=weekly&before_timestamp=

参数很简单,page是页码,count是每页图集数量,order是排序,before_timestamp为空,图虫由于是推送内容式的网站,所以before_timestamp应该是一个时间值,不一样的时间会显示不一样的内容,这里咱们把它丢弃,不考虑时间直接从最新的页面向前抓取。浏览器

请求结果为JSON格式内容,下降了抓取难度,结果以下:app

{
  "postList": [
    {
      "post_id": "15624611",
      "type": "multi-photo",
      "url": "https://weishexi.tuchong.com/15624611/",
      "site_id": "443122",
      "author_id": "443122",
      "published_at": "2017-10-28 18:01:03",
      "excerpt": "10月18日",
      "favorites": 4052,
      "comments": 353,
      "rewardable": true,
      "parent_comments": "165",
      "rewards": "2",
      "views": 52709,
      "title": "微风不燥  秋意正好",
      "image_count": 15,
      "images": [
        {
          "img_id": 11585752,
          "user_id": 443122,
          "title": "",
          "excerpt": "",
          "width": 5016,
          "height": 3840
        },
        {
          "img_id": 11585737,
          "user_id": 443122,
          "title": "",
          "excerpt": "",
          "width": 3840,
          "height": 5760
        },
        ...
      ],
      "title_image": null,
      "tags": [
        {
          "tag_id": 131,
          "type": "subject",
          "tag_name": "人像",
          "event_type": "",
          "vote": ""
        },
        {
          "tag_id": 564,
          "type": "subject",
          "tag_name": "美女",
          "event_type": "",
          "vote": ""
        }
      ],
      "favorite_list_prefix": [],
      "reward_list_prefix": [],
      "comment_list_prefix": [],
      "cover_image_src": "https://photo.tuchong.com/443122/g/11585752.webp",
      "is_favorite": false
    }
  ],
  "siteList": {...},
  "following": false,
  "coverUrl": "https://photo.tuchong.com/443122/ft640/11585752.webp",
  "tag_name": "美女",
  "tag_id": "564",
  "url": "https://tuchong.com/tags/%E7%BE%8E%E5%A5%B3/",
  "more": true,
  "result": "SUCCESS"
}

根据属性名称很容易知道对应的内容含义,这里咱们只需关心 postlist 这个属性,它对应的一个数组元素即是一个图集,图集元素中有几项属性咱们须要用到:dom

  • url:单个图集浏览的页面地址
  • post_id:图集编号,在网站中应该是惟一的,能够用来判断是否已经抓取过该内容
  • site_id:做者站点编号 ,构建图片来源连接要用到
  • title:标题
  • excerpt:摘要文字
  • type:图集类型,目前发现两种,一种multi-photo是纯照片,一种text是文字与图片混合的文章式页面,两种内容结构不一样,须要不一样的抓取方式,本例中只抓取纯照片类型,text类型直接丢弃
  • tags:图集标签,有多个
  • image_count:图片数量
  • images:图片列表,它是一个对象数组,每一个对象中包含一个img_id属性须要用到

根据图片浏览页面分析,基本上图片的地址都是这种格式: https://photo.tuchong.com/{site_id}/f/{img_id}.jpg ,很容易经过上面的信息合成。scrapy

2、建立项目

  1. 进入cmder命令行工具,输入workon scrapy 进入以前创建的虚拟环境,此时命令行提示符前会出现(Scrapy) 标识,标识处于该虚拟环境中,相关的路径都会添加到PATH环境变量中便于开发及使用。
  2. 输入 scrapy startproject tuchong 建立项目 tuchong
  3. 进入项目主目录,输入 scrapy genspider photo tuchong.com 建立一个爬虫名称叫 photo (不能与项目同名),爬取 tuchong.com 域名(这个须要修改,此处先输个大概地址),的一个项目内能够包含多个爬虫

通过以上步骤,项目自动创建了一些文件及设置,目录结构以下:

(PROJECT)
│  scrapy.cfg
│
└─tuchong
    │  items.py
    │  middlewares.py
    │  pipelines.py
    │  settings.py
    │  __init__.py
    │
    ├─spiders
    │  │  photo.py
    │  │  __init__.py
    │  │
    │  └─__pycache__
    │          __init__.cpython-36.pyc
    │
    └─__pycache__
            settings.cpython-36.pyc
            __init__.cpython-36.pyc
  • scrapy.cfg:基础设置
  • items.py:抓取条目的结构定义
  • middlewares.py:中间件定义,此例中无需改动
  • pipelines.py:管道定义,用于抓取数据后的处理
  • settings.py:全局设置
  • spiders\photo.py:爬虫主体,定义如何抓取须要的数据

3、主要代码

items.py 中建立一个TuchongItem类并定义须要的属性,属性继承自 scrapy.Field 值能够是字符、数字或者列表或字典等等:

import scrapy

class TuchongItem(scrapy.Item):
    post_id = scrapy.Field()
    site_id = scrapy.Field()
    title = scrapy.Field()
    type = scrapy.Field()
    url = scrapy.Field()
    image_count = scrapy.Field()
    images = scrapy.Field()
    tags = scrapy.Field()
    excerpt = scrapy.Field()
    ...

这些属性的值将在爬虫主体中赋予。

spiders\photo.py 这个文件是经过命令 scrapy genspider photo tuchong.com 自动建立的,里面的初始内容以下:

import scrapy

class PhotoSpider(scrapy.Spider):
    name = 'photo'
    allowed_domains = ['tuchong.com']
    start_urls = ['http://tuchong.com/']

    def parse(self, response):
        pass

爬虫名 name,容许的域名 allowed_domains(若是连接不属于此域名将丢弃,容许多个) ,起始地址 start_urls 将从这里定义的地址抓取(容许多个)
函数 parse 是处理请求内容的默认回调函数,参数 response 为请求内容,页面内容文本保存在 response.body 中,咱们须要对默认代码稍加修改,让其知足多页面循环发送请求,这须要重载 start_requests 函数,经过循环语句构建多页的连接请求,修改后代码以下:

import scrapy, json
from ..items import TuchongItem

class PhotoSpider(scrapy.Spider):
    name = 'photo'
    # allowed_domains = ['tuchong.com']
    # start_urls = ['http://tuchong.com/']

    def start_requests(self):
        url = 'https://tuchong.com/rest/tags/%s/posts?page=%d&count=20&order=weekly';
        # 抓取10个页面,每页20个图集
        # 指定 parse 做为回调函数并返回 Requests 请求对象
        for page in range(1, 11):
            yield scrapy.Request(url=url % ('美女', page), callback=self.parse)

    # 回调函数,处理抓取内容填充 TuchongItem 属性
    def parse(self, response):
        body = json.loads(response.body_as_unicode())
        items = []
        for post in body['postList']:
            item = TuchongItem()
            item['type'] = post['type']
            item['post_id'] = post['post_id']
            item['site_id'] = post['site_id']
            item['title'] = post['title']
            item['url'] = post['url']
            item['excerpt'] = post['excerpt']
            item['image_count'] = int(post['image_count'])
            item['images'] = {}
            # 将 images 处理成 {img_id: img_url} 对象数组
            for img in post.get('images', ''):
                img_id = img['img_id']
                url = 'https://photo.tuchong.com/%s/f/%s.jpg' % (item['site_id'], img_id)
                item['images'][img_id] = url

            item['tags'] = []
            # 将 tags 处理成 tag_name 数组
            for tag in post.get('tags', ''):
                item['tags'].append(tag['tag_name'])
            items.append(item)
        return items

通过这些步骤,抓取的数据将被保存在 TuchongItem 类中,做为结构化的数据便于处理及保存。

前面说过,并非全部抓取的条目都须要,例如本例中咱们只须要 type="multi_photo 类型的图集,而且图片太少的也不须要,这些抓取条目的筛选操做以及如何保存须要在pipelines.py中处理,该文件中默认已建立类 TuchongPipeline 并重载了 process_item 函数,经过修改该函数只返回那些符合条件的 item,代码以下:

...
    def process_item(self, item, spider):
        # 不符合条件触发 scrapy.exceptions.DropItem 异常,符合条件的输出地址
        if int(item['image_count']) < 3:
            raise DropItem("美女太少: " + item['url'])
        elif item['type'] != 'multi-photo':
            raise DropItem("格式不对: " + + item['url'])
        else:
            print(item['url'])
        return item
...

固然若是不用管道直接在 parse 中处理也是同样的,只不过这样结构更清晰一些,并且还有功能更多的FilePipelinesImagePipelines可供使用,process_item将在每个条目抓取后触发,同时还有 open_spiderclose_spider 函数能够重载,用于处理爬虫打开及关闭时的动做。

注意:管道须要在项目中注册才能使用,在 settings.py 中添加:

ITEM_PIPELINES = {
    'tuchong.pipelines.TuchongPipeline': 300, # 管道名称: 运行优先级(数字小优先)
}

另外,大多数网站都有反爬虫的 Robots.txt 排除协议,设置 ROBOTSTXT_OBEY = True 能够忽略这些协议,是的,这好像只是个君子协定。若是网站设置了浏览器User Agent或者IP地址检测来反爬虫,那就须要更高级的Scrapy功能,本文不作讲解。

4、运行

返回 cmder 命令行进入项目目录,输入命令:

scrapy crawl photo

终端会输出全部的爬行结果及调试信息,并在最后列出爬虫运行的统计信息,例如:

[scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 491,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,
 'downloader/response_bytes': 10224,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 2,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 11, 27, 7, 20, 24, 414201),
 'item_dropped_count': 5,
 'item_dropped_reasons_count/DropItem': 5,
 'item_scraped_count': 15,
 'log_count/DEBUG': 18,
 'log_count/INFO': 8,
 'log_count/WARNING': 5,
 'response_received_count': 2,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2017, 11, 27, 7, 20, 23, 867300)}

主要关注ERRORWARNING两项,这里的 Warning 实际上是不符合条件而触发的 DropItem 异常。

5、保存结果

大多数状况下都须要对抓取的结果进行保存,默认状况下 item.py 中定义的属性能够保存到文件中,只须要命令行加参数 -o {filename} 便可:

scrapy crawl photo -o output.json # 输出为JSON文件
scrapy crawl photo -o output.csv  # 输出为CSV文件

注意:输出至文件中的项目是未通过 TuchongPipeline 筛选的项目,只要在 parse 函数中返回的 Item 都会输出,所以也能够在 parse 中过滤只返回须要的项目

若是须要保存至数据库,则须要添加额外代码处理,好比能够在 pipelines.pyprocess_item 后添加:

...
    def process_item(self, item, spider):
        ...
        else:
            print(item['url'])
            self.myblog.add_post(item) # myblog 是一个数据库类,用于处理数据库操做
        return item
...

为了在插入数据库操做中排除重复的内容,可使用 item['post_id'] 进行判断,若是存在则跳过。

本项目中的抓取内容只涉及了文本及图片连接,并未下载图片文件,如需下载图片,能够经过两种方式:

  1. 安装 Requests 模块,在 process_item 函数中下载图片内容,同时在保存数据库时替换为本地图片路径。
  2. 使用 ImagePipelines 管道下载图片,具体使用方法下回讲解。
相关文章
相关标签/搜索