Python爬虫学习(七)----Scrapy框架实践

Scrapy框架

Scrapy框架是一个快速抓取web内容的框架,比我之前写的那个爬虫会更简单,更便捷。

事先说明

本人转载至http://blog.csdn.net/zjiang1994/article/details/52779537#comments
经原博主同意

具体分析

和原博主一样,我也是爬取慕课网的页面(http://www.imooc.com/course/list

下面是具体实现代码
因为慕课网的页面已经改变,所以我重新编写了选择器相关代码,和原博主一样采用xpath的方式。
难点已经注释,如有不懂,可以在评论区留下问题


MySpider.py
用来定义爬虫的基本信息和过滤器方法

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
__author__ = 'Gary'

# 引入库文件
import scrapy
from lxml import etree
from scrapytest.CourseItem import CourseItem

# 定义爬虫
class MySpider(scrapy.Spider):
    # 爬虫的名字,这个在后续会用到
    name = "myspider"
    # 允许访问的域
    allowed_domains = ["immoc.com"]
    # 爬取的初地址
    start_urls = ["http://www.imooc.com/course/list"]
    # 爬取方法
    def parse(self, response):
        # 实例一个容器保存一个爬取信息
        item = CourseItem()
        # 这部分是爬取部分,使用xpath 选择
        # 获取每个课程的div
        for box in response.xpath('//div[@class="course-card-container"]/a[@target="_blank"]'):
            # 获取每个div中的课程路径
            item['url'] = 'http://www.imooc.com' + box.xpath('.//@href').extract()[0]
            # 获取div中的课程标题
            item['title'] = box.xpath('.//div[@class="course-card-content"]/h3/text()').extract()[0]
            # 获取div中的标题图片地址
            item['image_url'] = box.xpath('.//div[@class="course-card-top"]/img/@src').extract()[0]
            # 获取div中的学生人数
            item['student'] = box.xpath('.//span/text()').extract()[1]
            # 获取div中的课程简介
            item['introduction'] = box.xpath('.//p/text()').extract()
            # 返回信息
            yield item
            # url跟进开始
            # 获取下一页的url信息
        url = response.xpath("//div[contains(.,'下一页')]//@href").extract()[-2]
        if url:
            # 将信息组合成下一页的url
            page = 'http://www.imooc.com' + url
            # 返回url
            # 停用过滤功能
            yield scrapy.Request(page, callback=self.parse, dont_filter=True)
            # url跟进结束

pipelines.py
用来与文件相关操作

最后爬取完的页面使用json文件存储的,然后图片下载在当前目录的images
你只需要在settting里这样设置

ITEM_PIPELINES = {
‘scrapytest.pipelines.MyPipeline’: 1,
‘scrapytest.pipelines.ImgPipleLine’: 100,
}
ITEM_PIPELINES是用于注册pipelines,逗号后的数字表示处理的优先级,1-1000


IMAGES_STORE = ‘/Users/wjh/Desktop/Python/web_crawler/scrapytest/images’
IMAGES_STORE是为了设置你图片下载完储存的目录


# -*- 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 scrapy
from scrapy.contrib.pipeline.images import ImagesPipeline
from scrapy.exceptions import DropItem
import json

class ScrapytestPipeline(object):
    def process_item(self, item, spider):
        return item

class MyPipeline(object):
    def __init__(self):
        # 打开文件
        self.file = open('data.json', 'w', encoding = 'utf-8')
    # 该方法用于处理数据
    def process_item (self, item, spider):
        # 读取item中的数据
        line = json.dumps(dict(item), ensure_ascii=False) + '\n'
        # 写入文件
        self.file.write(line)
        # 返回item
        return item
    # 该方法在spider被开启时被调用
    def open_spider(self, spider):
        pass
    def close_spider(self, spider):
        pass

class ImgPipleLine(ImagesPipeline):
    # 通过抓取的图片url获取一个Request用于下载
    def get_media_requests(self, item, info):
        # 返回Request 根据托盘url下载
        yield scrapy.Request('http:'+item['image_url'])
    # 当下载请求完成后执行该方法
    def item_completed(self, results, item, info):
        # 获取下载地址
        image_path = [x['path'] for ok, x in results if ok]
        # 判断是否成功
        if not image_path:
            raise DropItem('Item contains no images')
        # 将地址存入Item
        item['image_url'] = image_path
        return item

爬取结果如下

这里写图片描述

至此,爬虫的阶段暂一段落,分别利用了无框架和有框架结构,有兴趣想下载完整代码的同学可以访问我的Github,网址如下

以下为2个爬虫项目
https://github.com/Spacider/Spider
https://github.com/Spacider/Scrapy_Programming

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值