在自學Item Pipeline時遇到一個小問題:Scrapy的spider進不了pipeline(pipeline無法接收到Item對象)
1. items.py的代碼如下
# -*- coding: utf-8 -*-
import scrapy
class MypjtItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
title = scrapy.Field()
2. spider文件panta.py 的問題代碼如下
# -*- coding: utf-8 -*-
import scrapy
from ..items import MypjtItem
class PantaSpider(scrapy.Spider):
name = 'panta'
allowed_domains = ['sina.com.cn']
start_urls = ['http://sina.com.cn/']
def parse(self, response):
item = MypjtItem()
item['title'] = response.xpath("/html/head/title/text()")
print(item['title'])#輸出測試
3. settings.py 添加pipelines
ITEM_PIPELINES = {
'mypjt.pipelines.MypjtPipeline': 300,
}
4. pipelines.py代碼如下
# -*- coding: utf-8 -*-
import codecs
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class MypjtPipeline(object):
def __init__(self):
self.file = codecs.open("data1.txt", "wb", encoding="utf-8")
def process_item(self, item, spider):
I = str(item) + "\n"
print(I)
self.file.write(I)
return item
def close_spider(self, spider):
self.file.close()
5. 當在終端運行爬蟲時:
D:\PythonCodes\Scrapy\mypjt>scrapy crawl panta --nolog
[<Selector xpath='/html/head/title/text()' data='新浪首頁'>]
這里未打印出4中的“I”變量愉耙,而且生成的“data1.txt”文件中沒有內(nèi)容泵琳,經(jīng)過搜索發(fā)現(xiàn)在panta.py文件里的class PantaSpider中的parse()方法少了一個yield item
锉桑,加上這一句之后再在終端運行scrapy crawl panta --nolog
結(jié)果如下:
D:\PythonCodes\Scrapy\mypjt>scrapy crawl panta --nolog
[<Selector xpath='/html/head/title/text()' data='新浪首頁'>]
{'title': [<Selector xpath='/html/head/title/text()' data='新浪首頁'>]}
此為正確的結(jié)果蜓陌,并且在文件“data1.txt”中也出現(xiàn)內(nèi)容:
至于為什么用yield item
而不用return item
买窟,這里就要引用大佬的解釋說下“yield”關(guān)鍵字:
在python中赘艳,當你定義一個函數(shù)俺附,使用了yield關(guān)鍵字時萎庭,這個函數(shù)就是一個生成器,它的執(zhí)行會和其他普通的函數(shù)有很多不同光稼,函數(shù)返回的是一個對象或南,而不是你平常 所用return語句那樣孩等,能得到結(jié)果值。如果想取得值采够,那得調(diào)用next()函數(shù)肄方,如:
c = h() #h()包含了yield關(guān)鍵字
#返回值
> print c.next()
比如有的for in 操作的話,會自動的調(diào)用生成器的.next()方法蹬癌。
每當調(diào)用一次迭代器的next函數(shù)权她,生成器函數(shù)運行到y(tǒng)ield之處,返回yield后面的值且在這個地方暫停逝薪,所有> 的狀態(tài)都會被保持住隅要,直到下次next函數(shù)被調(diào)用,或者碰到異常循環(huán)退出董济。