Scrapy框架的学习(6.item介绍以及items的使用(提前定义好字段名))
生活随笔
收集整理的這篇文章主要介紹了
Scrapy框架的学习(6.item介绍以及items的使用(提前定义好字段名))
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在Scrapy框架中的items.py的作用
? 1.可以預先定義好要爬取的字段? ? ?items.py
import scrapyclass 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,TencentItem3class 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, TencentItem3class TencentPipeline(object):def process_item(self, item, spider):"""使用item的時候這里接收的是TencentItem類的對象,我們可以把它轉化字典"""print(dict(item))'''針對與不同的爬蟲字段類的對象,做不同的處理'''return item4. 這樣做有什么好處呢,個人理解:
(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 TencentItemclass TencentSpiderSpider(scrapy.Spider):passdef parse(self, response):passfor tr in tr_list:"""使用定義好的騰訊爬蟲的類的字段"""item = TencentItem()yield item? 在京東的爬蟲中,可以這樣使用
import scrapy # 導入不同爬蟲的類字段 from JD.items import JdItemclass JdSpiderSpider(scrapy.Spider):passdef parse(self, response):passfor tr in tr_list:"""使用定義好的騰訊爬蟲的類的字段"""item = JdItem()yield item3. 對于多個爬蟲,在pipelines,py中可以進行判斷,分別對不同的爬蟲的字段進行不同的處理
? ??isinstance() 函數來判斷一個對象是否是一個已知的類型
'''分別導入不同爬蟲的字段類''' from tencent.items import TencentItem, JdItem2class TencentPipeline(object):def process_item(self, item, spider):'''針對與不同的爬蟲字段類的對象,做不同的處理'''if isinstance(item, TencentItem):passif isinstance(item, JdItem2):passreturn item?
總結
以上是生活随笔為你收集整理的Scrapy框架的学习(6.item介绍以及items的使用(提前定义好字段名))的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Scrapy框架的学习(5.scarpy
- 下一篇: Scrapy框架的学习(7. 了解Scr