【发布时间】:2016-02-09 09:24:59
【问题描述】:
我正在尝试用爬虫蜘蛛去除 \r \n \t 字符,然后制作一个 json 文件。
我有一个充满新行的“描述”对象,但它没有做我想要的:将每个描述与标题匹配。
我尝试使用 map(unicode.strip()) 但它并没有真正起作用。作为scrapy的新手,我不知道是否有另一种更简单的方法或者map unicode是如何工作的。
这是我的代码:
def parse(self, response):
for sel in response.xpath('//div[@class="d-grid-main"]'):
item = xItem()
item['TITLE'] = sel.xpath('xpath').extract()
item['DESCRIPTION'] = map(unicode.strip, sel.xpath('//p[@class="class-name"]/text()').extract())
我也试过:
item['DESCRIPTION'] = str(sel.xpath('//p[@class="class-name"]/text()').extract()).strip()
但它引发了错误。最好的方法是什么?
【问题讨论】:
-
您好,“它实际上不起作用”是什么意思?
strip()只考虑前导字符和尾随字符,因此如果您想删除字符串内的任何内容,则需要其他方式。如果这是您的问题,import re和re.sub('[\r\n\t]', '', 'Hel\nlo\r!')会有所帮助。 -
我建议结帐
ItemLoaders doc.scrapy.org/en/latest/topics/loaders.html,它允许您管理Items 的输入和输出 -
QuentinPradet 谢谢,事实上保罗的回答很好,我不知道。还有花岗龙,我会研究的,谢谢