Item Loaders提供了一种便捷的方式填充抓取到的 :Items 。虽然Items可以使用自带的类字典形式API填充,但是Items Loaders提供了更便捷的API, 可以分析原始数据并对Item进行赋值。
从另一方面来说, Items 提供保存抓取数据的 容器 , 而 Item Loaders提供的是 填充 容器的机制。
Item Loaders提供的是一种灵活,高效的机制,可以更方便的被spider或source format (HTML, XML, etc)扩展,并override更易于维护的、不同的内容分析规则。
在 Spider 中典型的Item Loader的用法
from scrapy.loader import ItemLoader
from myproject.items import Product
def parse(self, response):
l = ItemLoader(item=Product(), response=response)#定义一个 ItemLoader
l.add_xpath('name', '//div[@class="product_name"]')
l.add_xpath('name', '//div[@class="product_title"]')
l.add_xpath('price', '//p[@id="price"]')
l.add_css('stock', 'p#stock]')
l.add_value('last_updated', 'today') # you can also use literal values
return l.load_item()
接下来对之前的程序进行再次更改,利用Item Loader进行填充
1.修改one_spider.py
class SamSpider(scrapy.Spider):
name = "sam"
start_urls = [
"https://maoyan.com/board/4"
]
url = 'https://maoyan.com/board/4'
def parse(self, response):
print('>'*50,'获取数据')
l = ItemLoader(item=SamzhuItem(), response=response)
for i in range(1,11):
l.add_xpath('name','//*[@id="app"]/div/div/div/dl/dd[%d]/div/div/div[1]/p[1]/a/@title'%i)
l.add_xpath('url', '//*[@id="app"]/div/div/div/dl/dd[%d]/div/div/div[1]/p[1]/a/@href'%i)
print(l.load_item())
print('>'*50,'获取下一页请求')
a=response.css('.list-pager li:last-child a::attr(href)').extract()[0] #选择到‘下一页’的按钮
if re.search(r'offset',a,re.M|re.I)!=None:
print('换页成功')
yield scrapy.Request(self.url+a, callback=self.parse) #返回一个requset,设置callback函数为parse
print('+'*50)
else:
print('到达终点')
2.运行 scrapy crawl sam
可以发现进行item填充时返回了刚刚获取的数据,dict+list的格式
小结:
ItemLoader objects | 说明 |
---|---|
get_value(value, *processors, **kwargs) | 通过给定的处理器和关键字参数处理给定值。 |
add_value (field_name, value, *processors, **kwargs) | 通过给定的处理器和关键字参数处理给定值。 |
replace_value (field_name, value, *processors, **kwargs) | 处理然后为给定字段添加给定值。 |
get_xpath (xpath, *processors, **kwargs) | 类似get_value() |
add_xpath (field_name, xpath, *processors, **kwargs) | 类似add_value() |
replace_xpath (field_name, xpath, *processors, **kwargs) | 类似replace_value() |
get_css (css, *processors, **kwargs) | 类似get_value() |
add_css (field_name, css, *processors, **kwargs) | 类似add_value() |
replace_css (field_name, css, *processors, **kwargs) | 类似replace_value() |
load_item () | 使用目前为止收集的数据填充项目,并将其返回 |
get_collected_values (field_name) | 返回给定字段的收集值 |
get_output_value (field_name) | 对于给定字段,返回使用输出处理器解析的收集值 |
get_input_processor (field_name) | 返回给定字段的输入处理器。 |
get_output_processor (field_name) | 返回给定字段的输出处理器。 |
item | |
context | |
default_item_class | |
default_input_processor | |
default_output_processor | |
default_selector_class | |
selector |