刮擦项目对象错误

2024-10-01 19:31:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我对报废物品对象有问题。当前的问题是,当我刮取某些字段时,我会像这样保存它们:

item['tag'] = response.xpath("//div[contains(@class, 'video-info-row showLess')]"
                                     "//a[contains(@href, '/video/search?search')]/text()").extract()

有多个标记在每次传递时被刮去并保存到item['tag']中。然后我去上传标签到我的SQL服务器,得到一个mySQL语法错误。这个问题非常明显,因为它试图插入如下内容:'tag1', u'tag2', u'tag3', u'tag4', u'tag5', u'tag6'。是否有任何方法可以去掉引号,因为我已经尝试过了。替换(“,”),但它不起作用。你知道吗


Tags: 对象divinfosearchresponsetagvideoitem
2条回答

您需要为该特定字段设置^{}输出处理器:

import scrapy
from scrapy.contrib.loader.processor import Join

class MyItem(scrapy.Item):
    my_field = scrapy.Field(output_processor=Join(separator=','))

为了建立在alecxe的答案之上,处理器只与项目加载器(http://doc.scrapy.org/en/latest/topics/loaders.html)一起工作:

def parse(self, response):
    l = ItemLoader(MyItem(), response)
    l.add_xpath('tag', '//a[@href="/video/search?search"]/text()')
    return l.load_item()

另一种解决方案是简单地使用join方法:

def parse(self, response):
    item = MyItem()
    item['tag'] = ','.join(response.xpath('//a[@href="/video/search?search"]/text()').extract())
    return item

相关问题 更多 >

    热门问题