如何在scrapy中使用项目字段订购xml?

Dio*_* Wu 2 python xml serialization scrapy

我写了一个蜘蛛,它会抓取一个网页并填充一个项目中的字段.该项目包含以下字段

class exampleitem():
    ex1 = Field()
    ex2 = Field()
    ex3 = Field()
    ... and so forth
Run Code Online (Sandbox Code Playgroud)

当我刮擦并导出到xml文件时,字段的顺序变得混乱并返回类似这样的内容

<items>
    <item>
        <ex2> <value> xyz </value> </ex2>
        <ex3> <value> abc </value> </ex3>
        <ex1> <value> ghi </value> </ex1>
    </item>
    ... so forth
</items>
Run Code Online (Sandbox Code Playgroud)

我想这样做,以便xml的格式按照它在我的item.py文件的Fields()中编写的确切顺序.

我一直在做研究过去一小时左右,我知道它与我的管道和使用xmlitemexporter有关,但我根本不知道如何定制我的管道甚至从哪里开始.

简而言之,我在行话中迷失方向,如果有人能指出我的方向,或者给我一个简短的示例代码,我将如何开始格式化我的剪切项目,我会很感激!

非常感谢

Guy*_*ely 5

scrapy项是python dict的包装器,将以不可预测的顺序返回项字段

def keys(self):
    return self._values.keys()
Run Code Online (Sandbox Code Playgroud)

更改您可以在您的项目中覆盖此功能,如:

class exampleitem(Item):
    ex1 = Field()
    ex2 = Field()
    ex3 = Field()

    def keys(self):
        return ['ext1', 'ext2', 'ext3']
Run Code Online (Sandbox Code Playgroud)

或者,以更通用的方式实现DictItem并使用python的OrderedDict而不是它当前使用的python的默认dict.