在Scrapy框架中的items.py的作用
1.可以预先定义好要爬取的字段 items.py
import scrapy class TencentItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() """定义好字段,并不代表真正的值,只是占一个位置,用的时候直接赋值就行""" position = scrapy.Field() category = scrapy.Field() date = scrapy.Field()
2. 把字段定义好之后 ,就可以在爬虫中进行使用
在用的时候, item的键名要和在items.py里面定义好的字段名称一致
import scrapy ''' 导入不同爬虫的类字段''' from tencent.items import TencentItem,TencentItem2,TencentItem3 class TencentSpiderSpider(scrapy.Spider): name = 'tencent_spider' allowed_domains = ['tencent.com'] start_urls = ['https://hr.tencent.com/position.php'] def parse(self, response): tr_list = response.xpath("//table[@class='tablelist']//tr")[1:-1] for tr in tr_list: """使用定义好的类""" item = TencentItem() """里面的键名,必须提前在items里面定义好之后才能用""" item["position"] = tr.xpath("./td/a/text()").extract_first() item["category"] = tr.xpath(".//td[2]/text()").extract_first() item["date"] = tr.xpath(".//td[5]/text()").extract_first() yield item
3. 如果想在pipelines.py中使用的方法是大同小异,只是在进行处理的时候item传过来的是一个类对象,要对其进行相应 的 转化
'''分别导入不同爬虫的字段类''' from tencent.items import TencentItem, TencentItem2, TencentItem3 class TencentPipeline(object): def process_item(self, item, spider): """使用item的时候这里接收的是TencentItem类的对象,我们可以把它转化字典""" print(dict(item)) '''针对与不同的爬虫字段类的对象,做不同的处理''' return item
4. 这样做有什么好处呢,个人理解:
(1) 可以直接看items.py,可以看出来要爬取那些字段
(2) 防止我们在item["键名"] 输入键名的时候输入错误
有多个爬虫时Item的处理
例如有个腾讯爬虫、有个京东爬虫,怎样处理
1. 在items.py里面创建不同的类,分别保存各自的字段
class TencentItem(scrapy.Item): """腾讯爬虫要爬取的字段""" """定义好字段,并不代表真正的值,只是占一个位置,用的时候直接赋值就行""" position = scrapy.Field() category = scrapy.Field() date = scrapy.Field() class JdItem(scrapy.Item): """京东爬虫要爬取的字段""" """定义好字段,并不代表真正的值,只是占一个位置,用的时候直接赋值就行""" position = scrapy.Field() category = scrapy.Field() date = scrapy.Field()
2. 然后在不同的爬虫程序里使用对应的类即可
在腾讯的爬虫里 , 导入和使用
import scrapy # 导入不同爬虫的类字段 from tencent.items import TencentItem class TencentSpiderSpider(scrapy.Spider): pass def parse(self, response): pass for tr in tr_list: """使用定义好的腾讯爬虫的类的字段""" item = TencentItem() yield item
在京东的爬虫中,可以这样使用
import scrapy # 导入不同爬虫的类字段 from JD.items import JdItem class JdSpiderSpider(scrapy.Spider): pass def parse(self, response): pass for tr in tr_list: """使用定义好的腾讯爬虫的类的字段""" item = JdItem() yield item
3. 对于多个爬虫,在pipelines,py中可以进行判断,分别对不同的爬虫的字段进行不同的处理
isinstance() 函数来判断一个对象是否是一个已知的类型
'''分别导入不同爬虫的字段类''' from tencent.items import TencentItem, JdItem2 class TencentPipeline(object): def process_item(self, item, spider): '''针对与不同的爬虫字段类的对象,做不同的处理''' if isinstance(item, TencentItem): pass if isinstance(item, JdItem2): pass return item