爬虫课程:scrapy及相关应用

 

以下是我的学习笔记,以及总结,如有错误之处请不吝赐教。

本文主要介绍Scrapy框架及相应应用代码。

Scrapy基础:

是一个用于爬行web站点和提取结构化数据的应用程序框架,可用于各种有用的应用程序,如数据挖掘、信息处理或历史档案,官网

scrapy结构包括:引擎(Scrapy Engine) 、调度器(Scheduler) 、下载器(Downloader) 、蜘蛛(Spiders) 、项目管道(Item Pipeline) 、下载器中间件(Downloader Middlewares) 、蜘蛛中间件(Spider Middlewares)、调度中间件(Scheduler Middlewares) ,如下图:

Scrapy工作方式:箭头表示的就是数据流向:

  • 从初始URL开始,Scheduler会将其交给Downloader进行下载
  • 下载之后会交给Spider进行分析 
  • Spider分析出来的结果有两种 :①一种是需要进一步抓取的链接,如 “下一页”的链接,它们会被传回Scheduler; ②一种是需要进一步抓取的链接,如 “下一页”的链接,它们会被传回Scheduler; 
  • 在数据流动的通道里还可以安装各种中间件,进行必要的处理。 

Scrapy应用:

  • Spider运行scrapy runspider spider.py -o xxx.json,推荐json、xml、csv格式,方便导入数据库。
  • Scrapy项目创建:scrapy startproject xxx
  • Scrapy shell:调试xpath网址
  • Scrapy spider 爬取流程:①先初始化请求URL列表,并指定下载后处理response的回调函数;②在parse回调中解析response并返回字典,Item对象,Request对象或它们的迭代对象;③在回调函数里面,使用选择器解析页面内容,并生成解析后的结果Item;④最后返回的这些Item通常会被持久化到数据库中(使用Item Pipeline)或者使用Feed exports将其保存到文件中。
    import scrapy
    
    class QQNewsSpider(scrapy.Spider):
        name = 'qqnews'
        start_urls = ['http://news.qq.com/society_index.shtml']
    
        def parse(self, response):
            for href in response.xpath('//*[@id="news"]/div/div/div/div/em/a/@href'):
                full_url = response.urljoin(href.extract())
                yield scrapy.Request(full_url, callback=self.parse_question)
    
        def parse_question(self, response):
            print response.xpath('//div[@class="qq_article"]/div/h1/text()').extract_first()
            print response.xpath('//span[@class="a_time"]/text()').extract_first()
            print response.xpath('//span[@class="a_catalog"]/a/text()').extract_first()
            print "\n".join(response.xpath('//div[@id="Cnt-Main-Article-QQ"]/p[@class="text"]/text()').extract())
            print ""
            yield {
                'title': response.xpath('//div[@class="qq_article"]/div/h1/text()').extract_first(),
                'content': "\n".join(response.xpath('//div[@id="Cnt-Main-Article-QQ"]/p[@class="text"]/text()').extract()),
                'time': response.xpath('//span[@class="a_time"]/text()').extract_first(),
                'cate': response.xpath('//span[@class="a_catalog"]/a/text()').extract_first(),
            }
    
  • Scrapy spider爬取方式

  1. 爬取1页内容:

    import scrapy
    
    class eduSpider(scrapy.Spider):
        name = "edu"
        start_urls = [
            'https://www.edu.com/category/index',
        ]
    
        def parse(self, response):
            for edu_class in response.xpath('//div[@class="course_info_box"]'):
                print(edu_class.xpath('a/h4/text()').extract_first())
                print(edu_class.xpath('a/p[@class="course-info-tip"][1]/text()').extract_first())
                print(edu_class.xpath('a/p[@class="course-info-tip"][2]/text()').extract_first())
                print( response.urljoin(edu_class.xpath('a/img[1]/@src').extract_first()))
                print( "\n")
    
                yield {
                    'title':edu_class.xpath('a/h4/text()').extract_first(),
                    'desc': edu_class.xpath('a/p[@class="course-info-tip"][1]/text()').extract_first(),
                    'time': edu_class.xpath('a/p[@class="course-info-tip"][2]/text()').extract_first(),
                    'img_url': response.urljoin(edu_class.xpath('a/img[1]/@src').extract_first())
                }
  2. 按照给定列表爬取多页:

    import scrapy
    
    class CnBlogSpider(scrapy.Spider):
        name = "cnblogs"
        allowed_domains = ["cnblogs.com"]
        start_urls = [
            'http://www.cnblogs.com/pick/#p%s' % p for p in xrange(1, 11)
            ]
    
        def parse(self, response):
            for article in response.xpath('//div[@class="post_item"]'):
                print article.xpath('div[@class="post_item_body"]/h3/a/text()').extract_first().strip()
                print response.urljoin(article.xpath('div[@class="post_item_body"]/h3/a/@href').extract_first()).strip()
                print article.xpath('div[@class="post_item_body"]/p/text()').extract_first().strip()
                print article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/a/text()').extract_first().strip()
                print response.urljoin(article.xpath('div[@class="post_item_body"]/div/a/@href').extract_first()).strip()
                print article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/span[@class="article_comment"]/a/text()').extract_first().strip()
                print article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/span[@class="article_view"]/a/text()').extract_first().strip()
                print ""
    
                yield {
                    'title': article.xpath('div[@class="post_item_body"]/h3/a/text()').extract_first().strip(),
                    'link': response.urljoin(article.xpath('div[@class="post_item_body"]/h3/a/@href').extract_first()).strip(),
                    'summary': article.xpath('div[@class="post_item_body"]/p/text()').extract_first().strip(),
                    'author': article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/a/text()').extract_first().strip(),
                    'author_link': response.urljoin(article.xpath('div[@class="post_item_body"]/div/a/@href').extract_first()).strip(),
                    'comment': article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/span[@class="article_comment"]/a/text()').extract_first().strip(),
                    'view': article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/span[@class="article_view"]/a/text()').extract_first().strip(),
                }
  3. “下一页”类型:

    import scrapy
    
    class QuotesSpider(scrapy.Spider):
        name = "quotes"
        start_urls = [
            'http://quotes.toscrape.com/tag/humor/',
        ]
    
        def parse(self, response):
            for quote in response.xpath('//div[@class="quote"]'):
                yield {
                    'text': quote.xpath('span[@class="text"]/text()').extract_first(),
                    'author': quote.xpath('span/small[@class="author"]/text()').extract_first(),
                }
    
            next_page = response.xpath('//li[@class="next"]/@herf').extract_first()
            if next_page is not None:
                next_page = response.urljoin(next_page)
                yield scrapy.Request(next_page, callback=self.parse)
  4. 按照链接进行爬取:

    import scrapy
    
    class StackOverflowSpider(scrapy.Spider):
        name = 'stackoverflow'
        start_urls = ['http://stackoverflow.com/questions?sort=votes']
    
        def parse(self, response):
            for href in response.xpath('//*[@class="question-summary"]/div[2]/h3/a/@href'):
                full_url = response.urljoin(href.extract())
                yield scrapy.Request(full_url, callback=self.parse_question)
    
        def parse_question(self, response):
            yield {
                'title': response.xpath('//*[@id="question-header"]/h1/a/text()').extract(),
                'votes': response.xpath('//span[@itemprop="upvoteCount"]/text()').extract_first(),
                'body': response.xpath('//*[@id="question"]/table/tbody/tr[1]/td[2]/div/div[1]/text()').extract(),
                'tags': ",".join(response.xpath('//div[@class="post-taglist"]/a/text()').extract()),
                'link': response.url,
            }
  • 不同类型spider

  1. CrawlSpider :链接爬取蜘蛛 ,属性rules:Rule对象列表,定义规则:

  2. XMLFeedSpider :XML订阅蜘蛛,通过某个指定的节点来遍历 :

  3. CSVFeedSpider :类似XML订阅蜘蛛,逐行迭代,调用parse_row()解析:

  • Scrapy组件Item:①保存数据的地方;

    ②Item Loader可方便填充 
  • Scrapy组件Item Pipeline :

  1. 当一个item被蜘蛛爬取到之后会被发送给Item Pipeline,然后多个组件按照顺序处理这个item;

  2. Item Pipeline常用场景:①清理HTML数据 ;②验证被抓取的数据(检查item是否包含某些字段) ;③重复性检查(然后丢弃) ;④将抓取的数据存储到数据库中 

  3. 定义一个Python类,实现方法process_item(self, item, spider)即可,返回一个字典或Item,或者抛出DropItem异常丢弃这个Item。

  4. 经常会实现以下的方法:①open_spider(self, spider) 蜘蛛打开的时执行;②close_spider(self, spider) 蜘蛛关闭时执行 ;f③rom_crawler(cls, crawler) 可访问核心组件比如配置和信号,并注册钩子函数到Scrapy中 

  5. 具体案例代码:


To be continue......

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值