Python爬虫scrapy

今天带来scrapy的第二讲,讲道理这个爬虫框架确实不错,但是用起来很多地方好坑,需要大家自己总结了,接下来我们先好好讲讲scrapy的用法机制。

1 命令行工具

list

列出当前项目中所有可用的spider。每行输出一个spider。

$ scrapy listspider1
spider2
fetch

使用Scrapy下载器(downloader)下载给定的URL,并将获取到的内容送到标准输出。

$ scrapy fetch --nolog http://www.example.com/some/page.html[ ... html content here ... ]
view

在浏览器中打开给定的URL,并以Scrapy spider获取到的形式展现。

$ scrapy view http://www.example.com/some/page.html[ ... browser starts ... ]
genspider

这仅仅是创建spider的一种快捷方法。该方法可以使用提前定义好的模板来生成spider。您也可以自己创建spider的源码文件。

$ scrapy genspider -t basic example example.com
Created spider 'example' using template 'basic' in module:
  mybot.spiders.example

2 Spiders

Spider类定义了如何爬取某个(或某些)网站。包括了爬取的动作(例如:是否跟进链接)以及如何从网页的内容中提取结构化数据(爬取item)。 换句话说,Spider就是您定义爬取的动作及分析某个网页(或者是有些网页)的地方。

基本方法这里不做讲解,来看一下今天要讲的。

  • start_requests()
    当spider启动爬取并且未制定URL时,该方法被调用。 当指定了URL时make_requests_from_url() 将被调用来创建Request对象。 该方法仅仅会被Scrapy调用一次,因此您可以将其实现为生成器。

如果您想要修改最初爬取某个网站的Request对象,您可以重写(override)该方法。 例如,如果您需要在启动时以POST登录某个网站,你可以这么写:

class MySpider(scrapy.Spider):
    name = 'myspider'

    def start_requests(self):
        return [scrapy.FormRequest(http://www.example.com/login,
                                   formdata={'user': 'john', 'pass': 'secret'},
                                   callback=self.logged_in)]    def logged_in(self, response):
        # here you would extract links to follow and return Requests for
        # each of them, with another callback
        pass

除了 start_urls 你也可以直接使用 start_requests()

import scrapyfrom myproject.items import MyItemclass MySpider(scrapy.Spider):
    name = 'example.com'
    allowed_domains = ['example.com']    def start_requests(self):
        yield scrapy.Request('http://www.example.com/1.html', self.parse)        yield scrapy.Request('http://www.example.com/2.html', self.parse)        yield scrapy.Request('http://www.example.com/3.html', self.parse)    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)

可以看到我们在这个spider里面没有写stat_url,直接通过start_requests方法进行爬取。

  • parse(response)
    这个方法大家已经不再陌生,而且用起来很简单。
    在单个回调函数中返回多个Request以及Item的例子:

import scrapyclass 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):
        sel = scrapy.Selector(response)        for h3 in response.xpath('//h3').extract():            yield {title: h3}        for url in response.xpath('//a/@href').extract():            yield scrapy.Request(url, callback=self.parse)
  • Spider arguments
    Spider arguments are passed through the crawl command using the -a
    option. For example:

import scrapyclass MySpider(scrapy.Spider):
    name = 'myspider'

    def __init__(self, category=None, *args, **kwargs):
        super(MySpider, self).__init__(*args, **kwargs)
        self.start_urls = ['http://www.example.com/categories/%s' % category]        # ...

注意这里的init方法,可以在里面定义start_urls。

scrapy crawl myspider -a category=electronics

我们运行上面这个命令,就是把category=electronics传给myspider。

  • 爬取规则(Crawling rules)
    接下来给出配合rule使用CrawlSpider的例子:

mport scrapyfrom scrapy.spiders import CrawlSpider, Rulefrom scrapy.linkextractors import LinkExtractorclass MySpider(CrawlSpider):
    name = 'example.com'
    allowed_domains = ['example.com']
    start_urls = ['http://www.example.com']

    rules = (        # 提取匹配 'category.php' (但不匹配 'subsection.php') 的链接并跟进链接(没有callback意味着follow默认为True)
        Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),        # 提取匹配 'item.php' 的链接并使用spider的parse_item方法进行分析
        Rule(LinkExtractor(allow=('item\.php', )), callback='parse_item'),
    )    def parse_item(self, response):
        self.logger.info('Hi, this is an item page! %s', response.url)

        item = scrapy.Item()
        item['id'] = response.xpath('//td[@id=item_id]/text()').re(r'ID: (\d+)')
        item['name'] = response.xpath('//td[@id=item_name]/text()').extract()
        item['description'] = response.xpath('//td[@id=item_description]/text()').extract()        return item

LinkExtractor是一个 Link Extractor 对象。 其定义了如何从爬取到的页面提取链接。 是一个 Link Extractor 对象。 其定义了如何从爬取到的页面提取链接。

callback是一个callable或string(该spider中同名的函数将会被调用)。 从link_extractor中每获取到链接时将会调用该函数。该回调函数接受一个response作为其第一个参数, 并返回一个包含 Item 以及(或) Request 对象(或者这两者的子类)的列表(list)。

注意我们这里callback = parse_item返回的就是item。

该spider将从example.com的首页开始爬取,获取category以及item的链接并对后者使用 parse_item方法。 当item获得返回(response)时,将使用XPath处理HTML并生成一些数据填入 Item 中。

3 Items

爬取的主要目标就是从非结构性的数据源提取结构性数据,例如网页。 Scrapy spider可以以python的dict来返回提取的数据.

Item使用简单的class定义语法以及 Field 对象来声明。例如:

import scrapyclass Product(scrapy.Item):
    name = scrapy.Field()
    price = scrapy.Field()
    stock = scrapy.Field()
    last_updated = scrapy.Field(serializer=str)
  • 创建item

>>> product = Product(name='Desktop PC', price=1000)>>> print product
Product(name='Desktop PC', price=1000)
  • 获取字段的值

>>> product['name']
Desktop PC>>> product.get('name')
Desktop PC>>> product['price']1000>>> product['last_updated']
Traceback (most recent call last):
    ...
KeyError: 'last_updated'>>> product.get('last_updated', 'not set')not set>>> product['lala'] # getting unknown fieldTraceback (most recent call last):
    ...
KeyError: 'lala'>>> product.get('lala', 'unknown field')'unknown field'>>> 'name' in product  # is name field populated?True>>> 'last_updated' in product  # is last_updated populated?False>>> 'last_updated' in product.fields  # is last_updated a declared field?True>>> 'lala' in product.fields  # is lala a declared field?False
  • 获取所有获取到的值

>>> product.keys()
['price', 'name']>>> product.items()
[('price', 1000), ('name', 'Desktop PC')]
  • 扩展Item
    您可以通过继承原始的Item来扩展item(添加更多的字段或者修改某些字段的元数据)。

class DiscountedProduct(Product):
    discount_percent = scrapy.Field(serializer=str)
    discount_expiration_date = scrapy.Field()

4 Item Pipeline

其实在之前我们就已经把数据放到item里面,并保存到本地json文件中。但发现好像还差点什么,没错就是Item Pipeline
以下是item pipeline的一些典型应用:

  • 清理HTML数据

  • 验证爬取的数据(检查item包含某些字段)

  • 查重(并丢弃)

  • 将爬取结果保存到数据库中

验证价格,同时丢弃没有价格的item

from scrapy.exceptions import DropItemclass PricePipeline(object):

    vat_factor = 1.15

    def process_item(self, item, spider):
        if item['price']:            if item['price_excludes_vat']:
                item['price'] = item['price'] * self.vat_factor            return item        else:            raise DropItem(Missing price in %s % item)

process_item(self, item, spider)每个item pipeline组件都需要调用该方法,这个方法必须返回一个具有数据的dict,或是 Item(或任何继承类)对象, 或是抛出 DropItem
异常,被丢弃的item将不会被之后的pipeline组件所处理。

将item写入JSON文件

以下pipeline将所有(从所有spider中)爬取到的item,存储到一个独立地 items.jl 文件,每行包含一个序列化为JSON格式的item:

import jsonclass JsonWriterPipeline(object):
    def __init__(self):
        self.file = open('items.jl', 'wb')    def process_item(self, item, spider):
        line = json.dumps(dict(item)) + \n
        self.file.write(line)        return item
Write items to MongoDB
import pymongoclass MongoPipeline(object):

    collection_name = 'scrapy_items'

    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
        )    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]    def close_spider(self, spider):
        self.client.close()    def process_item(self, item, spider):
        self.db[self.collection_name].insert(dict(item))        return item

上面的classmethod实际上是返回了一个MongoPipeline实例,并把mongo的参数初始化。

去重

一个用于去重的过滤器,丢弃那些已经被处理过的item。让我们假设我们的item有一个唯一的id,但是我们spider返回的多个item中包含有相同的id:

from scrapy.exceptions import DropItemclass DuplicatesPipeline(object):
    def __init__(self):
        self.ids_seen = set()    def process_item(self, item, spider):
        if item['id'] in self.ids_seen:            raise DropItem(Duplicate item found: %s % item)        else:
            self.ids_seen.add(item['id'])            return item

问题来了,我们的代码都写完了,但是这些pipiline代码放在哪里?
就是放在demo/demo/pipelines.py 里面,他同时可以定义多个类对item 进行处理。

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

这是默认的Pipeline代码,只有一个process_item方法。

为了启用一个Item Pipeline组件,你必须将它的类添加到 [ITEM_PIPELINES
(http://scrapychs.readthedocs.io/zh_CN/1.0/topics/settings.html#std:setting-ITEM_PIPELINES) 配置,就像下面这个例子:
ITEM_PIPELINES = {
'myproject.pipelines.PricePipeline': 300,
'myproject.pipelines.JsonWriterPipeline': 800,
}

作者:我是上帝可爱多

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用OpenCV实现视频去抖 整体步骤: 设置输入输出视频 寻找帧之间的移动:使用opencv的特征检测器,检测前一帧的特征,并使用Lucas-Kanade光流算法在下一帧跟踪这些特征,根据两组点,将前一个坐标系映射到当前坐标系完成刚性(欧几里得)变换,最后使用数组纪录帧之间的运动。 计算帧之间的平
前言 对中文标题使用余弦相似度算法和编辑距离相似度分析进行相似度分析。 准备数据集part1 本次使用的数据集来源于前几年的硕士学位论文,可根据实际需要更换。结构如下所示: 学位论文题名 基于卷积神经网络的人脸识别研究 P2P流媒体视频点播系统设计和研究 校园网安全体系的设计与实现 无线传感器网络中
前言 之前尝试写过一个爬虫,那时对网页请求还不够熟练,用的原理是:爬取整个html文件,然后根据标签页筛选有效信息。 现在看来这种方式无疑是吃力不讨好,因此现在重新写了一个爬取天气的程序。 准备工作 网上能轻松找到的是 101010100 北京这种编号,而查看中国气象局URL,他们使用的是北京545
前言 本文使用Python实现了PCA算法,并使用ORL人脸数据集进行了测试并输出特征脸,简单实现了人脸识别的功能。 1. 准备 ORL人脸数据集共包含40个不同人的400张图像,是在1992年4月至1994年4月期间由英国剑桥的Olivetti研究实验室创建。此数据集包含40个类,每个类含10张图
前言 使用opencv对图像进行操作,要求:(1)定位银行票据的四条边,然后旋正。(2)根据版面分析,分割出小写金额区域。 图像校正 首先是对图像的校正 读取图片 对图片二值化 进行边缘检测 对边缘的进行霍夫曼变换 将变换结果从极坐标空间投影到笛卡尔坐标得到倾斜角 根据倾斜角对主体校正 import
天气预报API 功能 从中国天气网抓取数据返回1-7天的天气数据,包括: 日期 天气 温度 风力 风向 def get_weather(city): 入参: 城市名,type为字符串,如西安、北京,因为数据引用中国气象网,因此只支持中国城市 返回: 1、列表,包括1-7的天气数据,每一天的分别为一个
数据来源:House Prices - Advanced Regression Techniques 参考文献: Comprehensive data exploration with Python 1. 导入数据 import pandas as pd import warnings warnin
同步和异步 同步和异步是指程序的执行方式。在同步执行中,程序会按顺序一个接一个地执行任务,直到当前任务完成。而在异步执行中,程序会在等待当前任务完成的同时,执行其他任务。 同步执行意味着程序会阻塞,等待任务完成,而异步执行则意味着程序不会阻塞,可以同时执行多个任务。 同步和异步的选择取决于你的程序需
实现代码 import time import pydirectinput import keyboard if __name__ == '__main__': revolve = False while True: time.sleep(0.1) if keyboard.is_pr
本文从多个角度分析了vi编辑器保存退出命令。我们介绍了保存和退出vi编辑器的命令,以及如何撤销更改、移动光标、查找和替换文本等实用命令。希望这些技巧能帮助你更好地使用vi编辑器。
Python中的回车和换行是计算机中文本处理中的两个重要概念,它们在代码编写中扮演着非常重要的角色。本文从多个角度分析了Python中的回车和换行,包括回车和换行的概念、使用方法、使用场景和注意事项。通过本文的介绍,读者可以更好地理解和掌握Python中的回车和换行,从而编写出更加高效和规范的Python代码。
SQL Server启动不了错误1067是一种比较常见的故障,主要原因是数据库服务启动失败、权限不足和数据库文件损坏等。要解决这个问题,我们需要检查服务日志、重启服务器、检查文件权限和恢复数据库文件等。在日常的数据库运维工作中,我们应该时刻关注数据库的运行状况,及时发现并解决问题,以确保数据库的正常运行。
信息模块是一种可重复使用的、可编程的、可扩展的、可维护的、可测试的、可重构的软件组件。信息模块的端接需要从接口设计、数据格式、消息传递、函数调用等方面进行考虑。信息模块的端接需要满足高内聚、低耦合的原则,以保证系统的可扩展性和可维护性。
本文从电脑配置、PyCharm版本、Java版本、配置文件以及程序冲突等多个角度分析了Win10启动不了PyCharm的可能原因,并提供了解决方法。
本文主要从多个角度分析了安装SQL Server 2012时可能出现的错误,并提供了解决方法。
Pycharm是一款非常优秀的Python集成开发环境,它可以让Python开发者更加高效地进行代码编写、调试和测试。在Pycharm中设置解释器非常简单,我们可以通过创建新项目、修改项目解释器、设置全局解释器等多种方式进行设置。
Python中有多种方法可以将字符串转换为整数,包括使用int()函数、try-except语句、正则表达式、map()函数、ord()函数和reduce()函数。在实际应用中,应根据具体情况选择最合适的方法。
本文介绍了导入CSV文件的多种方法,包括使用Excel、Python和R等工具。同时,还介绍了导入CSV文件时需要注意的一些细节和问题。CSV文件是数据处理和分析中不可或缺的一部分,希望本文能够对读者有所帮助。
mongodb是一种新型的数据库,它采用了面向文档的数据模型,具有灵活性、高性能和高可用性等优势。但是,mongodb也存在数据结构混乱、安全性和学习成本高等问题。
当Python运行不了时,我们应该从代码、Python环境、操作系统和硬件设备等多个角度来排查问题,并采取相应的解决措施。