Scrapy----Item Pipeline的一个小问题

在自学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”文件中没有内容,经过搜索发现在panta.py文件里的class PantaSpider中的parse()方法少了一个yield item,加上这一句之后再在终端运行scrapy crawl panta --nolog结果如下:
D:\PythonCodes\Scrapy\mypjt>scrapy crawl panta --nolog
[<Selector xpath='/html/head/title/text()' data='新浪首页'>]
{'title': [<Selector xpath='/html/head/title/text()' data='新浪首页'>]}

此为正确的结果,并且在文件“data1.txt”中也出现内容:

《Scrapy----Item Pipeline的一个小问题》

至于为什么用yield item而不用return item,这里就要引用大佬的解释说下“yield”关键字:

在python中,当你定义一个函数,使用了yield关键字时,这个函数就是一个生成器,它的执行会和其他普通的函数有很多不同,函数返回的是一个对象,而不是你平常 所用return语句那样,能得到结果值。如果想取得值,那得调用next()函数,如:

c = h() #h()包含了yield关键字   
#返回值  
> print  c.next() 

比如有的for in 操作的话,会自动的调用生成器的.next()方法。
每当调用一次迭代器的next函数,生成器函数运行到yield之处,返回yield后面的值且在这个地方暂停,所有> 的状态都会被保持住,直到下次next函数被调用,或者碰到异常循环退出。

6. 总结:Item 对象是自定义的 python 字典。我们可以使用标准的字典语法来赋值或获取到其每个字段的值;而且在后续的处理中如果我们还要用到获取到的数据,那么Spider 应该将爬取到的数据以 Item 对象返回,所以要加上yield item这样一句代码。开始的错误代码没有将Item对象返回,因此pipelines.py文件里的 process_item()方法中的item没有值,也就无法打出结果

    原文作者:PantAsuna
    原文地址: https://www.jianshu.com/p/69ec9f42c6e0
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞