scrapy - 项目加载器 - 默认处理器 [英] scrapy - item loader - default processors

查看:47
本文介绍了scrapy - 项目加载器 - 默认处理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python和scrapy的新手,所以我提前为一些愚蠢的问题道歉.我在使用默认项目加载器的处理器时遇到了一些问题,以及相关问题:

I'm new to python and scrapy, so I apologise for maybe silly questions in advance. I have some troubles with default item loader's processors, and related questions:

  1. 我使用 default_input_processor 变量使用 TakeFirst() 处理器从列表中提取第一个值,如下所示:

  1. I use default_input_processor variable to extract first value from list using TakeFirst() processor like that:

class    CaseLoader(scrapy.loader.ItemLoader):
    default_input_processor = TakeFirst()

和用法:

  def load_row_data(self, row):
      cl = CaseLoader(CaseItem(), row)

      cl.add_xpath('case_num',  './/td[1]/a/text()')
      cl.add_xpath('case_link', './/td[1]/a/@href')
      cl.add_xpath('name',      './/td[3]/text()')
      return cl.load_item()

然后我从回调方法中产生这个项目,但 TakeFirst() 不起作用,我得到一个列表而不是字符串.如果我使用 TakeFist() 作为 default_output_processor,它就可以工作.default_input_processor 如何工作?为什么在这种情况下不应用 TakeFisrt() 处理器?

then I yield this item from callback methos, but TakeFirst() doesn't work, I get a list instead of string. If I use TakeFist() as default_output_processor, it works. How does default_input_processor works? Why TakeFisrt() processor isn't applied in this case?

文档中,我看到了 unicode 的用法.剥离方法:

In documentation I saw usage of unicode.strip method:

from scrapy.loader import ItemLoader
from scrapy.loader.processors import TakeFirst, MapCompose, Join

class ProductLoader(ItemLoader):

    default_output_processor = TakeFirst()

    name_in = MapCompose(unicode.title)
    name_out = Join()

    rice_in = MapCompose(unicode.strip)

    # ...

但是当我尝试在 Compose() 的 Item Loader 中使用它时,出现错误:

But when I tried to use it in my Item Loader in Compose() I get error:

NameError: name 'unicode' is not defined

如果我理解正确,此方法应该从字符串的开头和结尾删除空格.如何正确使用?我是否需要编写代码并改用我的条带功能?

If I understand right this method should remove white spaces from beginning and end of the string. How to use it properly? Do I need to code and use my strip function instead?

推荐答案

那是因为文档用的是 Python2 而你用的是 Python3

That is because the documentation is using Python2 and you are using Python3

Python3 中没有 unicode.你应该使用 str 代替

There is no unicode in Python3. You should use str instead

class ProductLoader(ItemLoader):

    default_output_processor = TakeFirst()

    name_in = MapCompose(str.title)
    name_out = Join()

    rice_in = MapCompose(str.strip)

有关更多信息,请参阅下面的线程

See below thread also for more information

NameError:全局名称unicode"不是定义 - 在 Python 3 中

这篇关于scrapy - 项目加载器 - 默认处理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆