Scrapy基本概念——Items

一、Items

Item对象只是一个容器,用来保存爬取到的数据, 它提供了类似于字典的API。说白了,Item对象和字段(Field)对象都是一个字典,只不过Item对象增加了一个fields属性

二、声明Item

import scrapy
class 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)

四、获取Item的字段

>>> 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 field
Traceback (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

五、设置Item的字段

>>> product['last_updated'] = 'today'
>>> product['last_updated']
today
>>> product['lala'] = 'test' # setting unknown field
Traceback (most recent call last):
    ...
KeyError: 'Product does not support field: lala'

六、获取Item的所有字段

>>> product.keys()
['price', 'name']
>>> product.items()
[('price', 1000), ('name', 'Desktop PC')]
>>> product.fields
{'name': {}, 'price': {}, 'stock': {}}

七、其他任务

1、复制Item

>>> product2 = Product(product)
>>> print product2
Product(name='Desktop PC', price=1000)
>>> product3 = product2.copy()
>>> print product3
Product(name='Desktop PC', price=1000)

2、根据Item创建字典(dict)

>>> dict(product) # create a dict from all populated values
{'price': 1000, 'name': 'Desktop PC'}

3、根据字典(dict)创建Item

>>> Product({'name': 'Laptop PC', 'price': 1500})
Product(price=1500, name='Laptop PC')
>>> Product({'name': 'Laptop PC', 'lala': 1500}) # warning: unknown field in dict
Traceback (most recent call last):
    ...
KeyError: 'Product does not support field: lala'

八、扩展Item

您可以通过继承原始的Item来扩展item(添加更多的字段或者修改某些字段的数据)

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

您也可以通过使用原字段的数据添加新的字段或修改原来的字段来扩展字段的数据

class SpecificProduct(Product):
    name = scrapy.Field(Product.fields['name'], serializer=my_serializer)

这段代码在保留所有原来数据的情况下添加(或者覆盖)了name字段的serializer

更多爬虫知识以及实例源码,可关注微信公众号:angry_it_man

你可能感兴趣的:(JavaScript,scrapy,服务器,java,爬虫,python)