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,
}

作者:我是上帝可爱多

相关文章

本文从多个角度分析了vi编辑器保存退出命令。我们介绍了保存...
Python中的回车和换行是计算机中文本处理中的两个重要概念,...
SQL Server启动不了错误1067是一种比较常见的故障,主要原因...
信息模块是一种可重复使用的、可编程的、可扩展的、可维护的...
本文从电脑配置、PyCharm版本、Java版本、配置文件以及程序冲...
本文主要从多个角度分析了安装SQL Server 2012时可能出现的错...