【发布时间】:2018-01-25 00:59:12
【问题描述】:
我最近开始学习 Scrapy(以及 Python),但遇到了一个特殊的问题,到目前为止我还没有找到解释。我设法找到了一种解决方法(见下文),但很想了解 .extract() 行为背后的原因。
在我的解析函数中运行以下代码
item['stops'] = response.xpath('//td[@class="station"]/a[@href]/text()').extract
导致 Scrapy 保存的不是定义的输出 csv 中的数据,而是完整的字符串(?),如下所示:
<bound method SelectorList.extract of
[<Selector xpath='//td[@class="station"]/a[@href]/text()' data=u'K\xf6ln Hbf'>,
<Selector xpath='//td[@class="station"]/a[@href]/text()' data=u'Siegburg/Bonn'>,
<Selector xpath='//td[@class="station"]/a[@href]/text()' data=u'Frankfurt(M) Flughafen Fernbf'>,
<Selector xpath='//td[@class="station"]/a[@href]/text()' data=u'Mannheim Hbf'>,
<Selector xpath='//td[@class="station"]/a[@href]/text()' data=u'Karlsruhe Hbf'>,
<Selector xpath='//td[@class="station"]/a[@href]/text()' data=u'Offenburg'>,
<Selector xpath='//td[@class="station"]/a[@href]/text()' data=u'Freiburg(Breisgau) Hbf'>,
<Selector xpath='//td[@class="station"]/a[@href]/text()' data=u'Basel Bad Bf'>,
<Selector xpath='//td[@class="station"]/a[@href]/text()' data=u'Basel SBB'>]>
数据已正确分配,但未按原样传递给元素。使用 .re() 而不是 .extract() 运行的其他功能可以正常工作。 令人惊讶的是,如果我按以下方式运行上述查询,它也可以正常工作
item['stops'] = response.xpath('//td[@class="station"]/a[@href]/text()').re('.*')
【问题讨论】:
-
没有括号,
response.xpath(......).extract是SelectorList上的一个方法。您需要实际调用该方法,您应该没问题:item['stops'] = response.xpath('//td[@class="station"]/a[@href]/text()').extract() -
啊啊啊,谢谢!我不敢相信我没有注意到这一点 - 非常感谢!
标签: scrapy