如何序列化作为XML导出器中项目列表的Scrapy字段

时间:2019-07-19 10:24:01

标签: python xml serialization scrapy exporter

我构建了复杂的项目,其中字段可能是其他项目类型的列表。当我使用默认的XmlItemExporter导出时,子列表项的前缀为<value>标签。我正在寻找有关如何将子项标识符分配给这些值标签的示例。

文档的“项目导出器”页面解释了这句话:

  

除非在serialize_field()方法中被覆盖,否则通过对<value>元素内的每个值进行序列化来导出多值字段。这是为了方便起见,因为多值字段非常常见。

docs页面还给出了在字段中声明序列化器覆盖Serialize_Field()方法的简单示例,但是这两个都是针对单值字段,没有建议如何为多值字段自定义它们。

我在网上搜索了一个示例,但没有找到任何示例。

这是我用于测试的示例项目树:

class Course(scrapy.Item):
    title = scrapy.Field()
    lessons = scrapy.Field()

class Lesson(scrapy.Item):
    session = scrapy.Field()
    topic = scrapy.Field()
    assignment = scrapy.Field()

class ReadingAssignment(scrapy.Item):
    textBook = scrapy.Field()
    pages = scrapy.Field()

course = Course()
course['title'] = 'Greatness'
course['lessons'] = []

lesson = Lesson()
lesson['session'] = 'Week 1'
lesson['topic'] = 'Think Great'
lesson['assignment'] = []

reading =  ReadingAssignment()
reading['textBook'] = 'Great Book 1'
reading['pages'] = '1-20'
lesson['assignment'].append(reading)
course['lessons'].append(lesson)

lesson = Lesson()
lesson['session'] = 'Week 2'
lesson['topic'] = 'Act Great'
lesson['assignment'] = []

reading =  ReadingAssignment()
reading['textBook'] = 'Great Book 2'
reading['pages'] = '21-40'
lesson['assignment'].append(reading)
course['lessons'].append(lesson)

lesson = Lesson()
lesson['session'] = 'Week 3'
lesson['topic'] = 'Look Great'
lesson['assignment'] = []

reading =  ReadingAssignment()
reading['textBook'] = 'Great Book 3'
reading['pages'] = '41-60'
lesson['assignment'].append(reading)
course['lessons'].append(lesson)

lesson = Lesson()
lesson['session'] = 'Week 4'
lesson['topic'] = 'Be Great'
lesson['assignment'] = []

reading =  ReadingAssignment()
reading['textBook'] = 'Great Book 4'
reading['pages'] = '61-80'
lesson['assignment'].append(reading)
course['lessons'].append(lesson)

输出:

>>> course
{'lessons': [{'assignment': [{'pages': '1-20', 'textBook': 'Great Book 1'}],
              'session': 'Week 1',
              'topic': 'Think Great'},
             {'assignment': [{'pages': '21-40', 'textBook': 'Great Book 2'}],
              'session': 'Week 2',
              'topic': 'Act Great'},
             {'assignment': [{'pages': '41-60', 'textBook': 'Great Book 3'}],
              'session': 'Week 3',
              'topic': 'Look Great'},
             {'assignment': [{'pages': '61-80', 'textBook': 'Great Book 4'}],
              'session': 'Week 4',
              'topic': 'Be Great'}],
 'title': 'Greatness'}

通过XmlItemExporter运行此命令时,我得到:

<?xml version="1.0" encoding="utf-8"?>
<items>
  <course>
    <title>Greatness</title>
    <lessons>
      <value>
        <session>Week 1</session>
        <topic>Think Great</topic>
        <assignment>
          <value>
            <textBook>Great Book 1</textBook>
            <pages>1-20</pages>
          </value>
        </assignment>
      </value>
      <value>
        <session>Week 2</session>
        <topic>Act Great</topic>
        <assignment>
          <value>
            <textBook>Great Book 2</textBook>
            <pages>21-40</pages>
          </value>
        </assignment>
      </value>
      <value>
        <session>Week 3</session>
        <topic>Look Great</topic>
        <assignment>
          <value>
            <textBook>Great Book 3</textBook>
            <pages>41-60</pages>
          </value>
        </assignment>
      </value>
      <value>
        <session>Week 4</session>
        <topic>Be Great</topic>
        <assignment>
          <value>
            <textBook>Great Book 4</textBook>
            <pages>61-80</pages>
          </value>
        </assignment>
      </value>
    </lessons>
  </course>
</items>

我想做的是将那些<value>标记更改为附加到列表中的项的名称。像这样:

<items>
  <course>
    <title>Greatness</title>
    <lessons>
      <lesson>
        <session>Week 1</session>
        <topic>Think Great</topic>
        <assignment>
          <reading>
            <textBook>Great Book 1</textBook>
            <pages>1-20</pages>
          </reading>
        </assignment>
      </lesson>
      <lesson>
        <session>Week 2</session>
        <topic>Act Great</topic>
        <assignment>
          <reading>
            <textBook>Great Book 2</textBook>
            <pages>21-40</pages>
          </reading>
        </assignment>
      </lesson>
      <lesson>
        <session>Week 3</session>
        <topic>Look Great</topic>
        <assignment>
          <reading>
            <textBook>Great Book 3</textBook>
            <pages>41-60</pages>
          </reading>
        </assignment>
      </lesson>
      <lesson>
        <session>Week 4</session>
        <topic>Be Great</topic>
        <assignment>
          <reading>
            <textBook>Great Book 4</textBook>
            <pages>61-80</pages>
          </reading>
        </assignment>
      </lesson>
    </lessons>
  </course>
</items>

1 个答案:

答案 0 :(得分:0)

这确实没有得到很好的记录,我们不得不求助于阅读XmlItemExporter source code,结果发现<value>标签选择已硬编码在{{3}中}:

elif is_listlike(serialized_value):
    self._beautify_newline()
    for value in serialized_value:
        self._export_xml_field('value', value, depth=depth+1)
    self._beautify_indent(depth=depth)

幸运的是,在前几行有出路:

if hasattr(serialized_value, 'items'):
    self._beautify_newline()
    for subname, value in serialized_value.items():
        self._export_xml_field(subname, value, depth=depth+1)
    self._beautify_indent(depth=depth)

这本来是用来处理 dictionary 的,但是实际上,它将采用具有.items()方法的任何东西来返回字符串和项的元组!

但是,导出器中缺少一个重要步骤:递归。您基本上只能在顶级项目字段上设置serializer标志,当前Scrapy实现会完全忽略顶级项目中Field()子类上的任何Item元素。每个导出器在驱动内部XmlItemExporter._export_xml_field() method方面都有各自的特点,因此我们无法预先处理递归,因为每个特定的导出器(JSON,XML等)在序列化字段方面的方式有所不同。我们可以使用XmlItemExporter类的子类来解决此问题,详情请参见下文。

因此,这里的第一个技巧是创建一个具有.items()方法并为您提供<container>标签的专用对象。请注意,您必须自己处理序列化的递归! Scrapy序列化程序本身不会将递归处理为嵌套结构:

class CustomXMLValuesSerializer:
    @classmethod
    def serialize_as(cls, name):
        def serializer(items, serialize):
            return cls(name, items, serialize)
        return serializer

    def __init__(self, name, items, serialize=None):
        self._name = name
        self._items = items
        self._serialize = serialize if serialise is not None else lambda x: x

    def items(self):
        for item in self._items:
            yield (self._name, self._serialize(item))

然后使用CustomXMLValuesSerializer.serialize_as()类方法为列表字段创建自定义序列化程序:

class Course(scrapy.Item):
    title = scrapy.Field()
    lessons = scrapy.Field(
        serializer=CustomXMLValuesSerializer.serialize_as("lesson")
    )

class Lesson(scrapy.Item):
    session = scrapy.Field()
    topic = scrapy.Field()
    assignment = scrapy.Field(
        serializer=CustomXMLValuesSerializer.serialize_as("reading")
    )

class ReadingAssignment(scrapy.Item):
    textBook = scrapy.Field()
    pages = scrapy.Field()

最后,我们需要一个稍微定制的导出器,该导出器实际上可以让我们递归处理嵌套项目:

from functools import partial

class RecursingXmlItemExporter(XmlItemExporter):
    def _recursive_serialized_fields(self, item):
        if isinstance(item, scrapy.Item):
            return dict(self._get_serialized_fields(item, default_value=''))
        return item

    def serialize_field(self, field, name, value):
        serializer = field.get('serializer', lambda x: x)
        try:
            return serializer(value, self._recursive_serialized_fields)
        except TypeError:
            return serializer(value)

请注意,这是由于BaseItemExporter._get_serialized_fields() method传入default_value=''

请确保使用此自定义导出器,因为它会在必需的上下文中传递以序列化嵌套项:

exporter = RecursingXmlItemExporter(some_file, indent=2, item_element='course')
exporter.start_exporting()
exporter.export_item(course)
exporter.finish_exporting()

现在,实际上是使用name字符串作为容器元素来导出容器了:

<?xml version="1.0" encoding="utf-8"?>
<items>
  <course>
    <title>Greatness</title>
    <lessons>
      <lesson>
        <session>Week 1</session>
        <topic>Think Great</topic>
        <assignment>
          <reading>
            <textBook>Great Book 1</textBook>
            <pages>1-20</pages>
          </reading>
        </assignment>
      </lesson>
      <lesson>
        <session>Week 2</session>
        <topic>Act Great</topic>
        <assignment>
          <reading>
            <textBook>Great Book 2</textBook>
            <pages>21-40</pages>
          </reading>
        </assignment>
      </lesson>
      <lesson>
        <session>Week 3</session>
        <topic>Look Great</topic>
        <assignment>
          <reading>
            <textBook>Great Book 3</textBook>
            <pages>41-60</pages>
          </reading>
        </assignment>
      </lesson>
      <lesson>
        <session>Week 4</session>
        <topic>Be Great</topic>
        <assignment>
          <reading>
            <textBook>Great Book 4</textBook>
            <pages>61-80</pages>
          </reading>
        </assignment>
      </lesson>
    </lessons>
  </course>
</items>

我和Scrapy一起that's what the base XmlItemExporter.export_item() implementation uses来查看项目是否有兴趣更好地支持嵌套Item结构。

另一种方法是使用对XmlItemExporter.export_item()方法的单独调用来导出嵌套项目,但是这要求导出器可以在与序列化程序相同的名称空间中以全局方式访问,或者将导出器子类化然后将导出器传递给序列化器。然后,您必须满足XmlItemExporter.export_item()硬编码缩进这一事实。