scrapy 的三个入门应用场景

news/2024/7/19 11:48:31 标签: python, 爬虫

说明
本文参照了官网的 dmoz 爬虫例子。

不过这个例子有些年头了,而 dmoz.org 的网页结构已经不同以前。所以我对xpath也相应地进行了修改

概要
本文提出了scrapy 的三个入门应用场景

  1. 爬取单页
  2. 根据目录页面,爬取所有指向的页面
  3. 爬取第一页,然后根据第一页的连接,再爬取下一页...。依此,直到结束

对于场景二、场景三可以认为都属于:链接跟随(Following links)

链接跟随的特点就是:在 parse 函数结束时,必须 yield 一个带回调函数 callback 的 Request 类的实例

本文基于:windows 7 (64) + python 3.5 (64) + scrapy 1.2

场景一

描述

爬取单页内容

示例代码

python">python">import scrapy

from tutorial.items import DmozItem

class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allowed_domains = ["dmoz.org"]

    start_urls = [
        "http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
        "http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
    ]

    def parse(self, response):        
        for div in response.xpath('//div[@class="title-and-desc"]'):
            item = DmozItem()
            item['title'] = div.xpath('a/div/text()').extract_first().strip()
            item['link'] = div.xpath('a/@href').extract_first()
            item['desc'] = div.xpath('div[@class="site-descr "]/text()').extract_first().strip()
            yield item

场景二

描述

  • ①进入目录,提取连接。
  • ②然后爬取连接指向的页面的内容
    其中①的yield scrapy.Request的callback指向②

官网描述:

...extract the links for the pages you are interested, follow them and then extract the data you want for all of them.

示例代码

python">python">import scrapy

from tutorial.items import DmozItem

class DmozSpider(scrapy.Spider):
    name = "dmoz"
    allowed_domains = ["dmoz.org"]

    start_urls = [
        'http://www.dmoz.org/Computers/Programming/Languages/Python/' # 这是目录页面
    ]
    
    def parse(self, response):
        for a in response.xpath('//section[@id="subcategories-section"]//div[@class="cat-item"]/a'):
            url = response.urljoin(a.xpath('@href').extract_first().split('/')[-2])
            yield scrapy.Request(url, callback=self.parse_dir_contents)
        
        
    def parse_dir_contents(self, response):
        for div in response.xpath('//div[@class="title-and-desc"]'):
            item = DmozItem()
            item['title'] = div.xpath('a/div/text()').extract_first().strip()
            item['link'] = div.xpath('a/@href').extract_first()
            item['desc'] = div.xpath('div[@class="site-descr "]/text()').extract_first().strip()
            yield item

场景三

描述

  • ①进入页面,爬取内容,并提取下一页的连接。
  • ②然后爬取下一页连接指向的页面的内容
    其中①的yield scrapy.Request的callback指向①自己

官网描述:

A common pattern is a callback method that extracts some items, looks for a link to follow to the next page and then yields a Request with the same callback for it

示例代码

python">python">import scrapy

from myproject.items import MyItem

class MySpider(scrapy.Spider):
    name = 'example.com'
    allowed_domains = ['example.com']

    start_urls = [
        'http://www.example.com/1.html',
        'http://www.example.com/2.html',
        'http://www.example.com/3.html',
    ]

    def parse(self, response):
        for h3 in response.xpath('//h3').extract():
            yield MyItem(title=h3)

        for url in response.xpath('//a/@href').extract():
            yield scrapy.Request(url, callback=self.parse)
            

说明
第三个场景未测试!


http://www.niftyadmin.cn/n/1291540.html

相关文章

鸿蒙玩王者荣耀,王者荣耀鸿蒙版

王者荣耀鸿蒙版是一款王者荣耀题材的策略竞技类moba手游。这款游戏有着刺激的推塔类玩法,这款游戏中完善的系统功能,所以玩家可以轻松竞技,其中的所有的英雄可以更好的竞技,同时游戏中的英雄可以自由选择搭配阵容,你需…

CodeForces 711D Directed Roads

计数,模拟。 首先观察一下给出的图的特点: $1.$一定存在环。 $2.$可能存在多个环。 我们对每个环计算方案数,假设环$C$上包含$x$条边,那么把环$C$破坏掉的方案数有${2^x} - 2$种。 那么答案就是每个环的方案数乘起来,再…

c语言不被O2优化,【图片】今天写几个性能测试,为什么C语言跑得这么慢呢??【c语言吧】_百度贴吧...

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼易言版本……跑100000万成绩不如PHP。。。。.版本 2.程序集 程序集1.子程序 _启动子程序, 整数型, , 本子程序在程序启动后最先执行.局部变量 参数, 文本型, , "0".局部变量 to, 整数型.局部变量 fr, 整数型.局部变量 n,…

性能指标术语理发店模型

2015-11-26 09:13:53 响应时间 响应时间呈现时间系统响应时间 呈现时间取决于数据在被客户端收后到呈现出页面所消耗的时间; 系统响应时间指应用系统从请求发出开始到客户端接收到数据所消耗的时间。 通常可以认为:响应时间系统响应时间 对一个web应用来…

一加6升级Android9.0,尝鲜安卓9.0? 升级需谨慎!

原标题:尝鲜安卓9.0? 升级需谨慎!上周开始,谷歌正式开始推送Android 9.0大版本,新版本新增了对刘海屏显示内容的优化,同时加入了更多的AI支持,还有全新的手势操作和界面等。除了谷歌亲儿子之外&…

自定义iOS7导航栏背景,标题和返回按钮文字颜色

转自:http://blog.csdn.net/mad1989/article/details/41516743 在iOS7下,默认导航栏背景,颜色是这样的,接下来我们就进行自定义,如果你仅仅是更改一下背景和颜色,代码会很简单,不需要很复杂的自定义View来替…

select2去除搜索框

$("#type_select").select2({minimumResultsForSearch: -1});

android 通知类型,Android消息通知栏的实现方法介绍

背景知识:可以用Activity和Service来开始消息通知,两者的区别在于一个是在前台触发,一个是后台服务触发。要使用消息通知,必须要用到两个类:NotificationManager和Notification,其他NotificationManager的初…