0

我的解析如下所示:

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    titles = hxs.select("//tr/td")
    items = []
    for titles in titles:
        item = MyItem()
        item['title'] = titles.select('h3/a/text()').extract()
        items.append(item)
    return items

为什么会这样输出json:

[{"title": ["random title #1"]},
{"title": ["random title #2"]}]
4

2 回答 2

2

titles.select('h3/a/text()').extract()返回一个列表,所以你得到一个列表。Scrapy 不对您的项目结构做出任何假设。

快速解决方法是获得第一个结果:

item['title'] = titles.select('h3/a/text()').extract()[0]

更好的解决方案是使用项目加载器并TakeFirst()用作输出处理器:

from scrapy.contrib.loader import XPathItemLoader
from scrapy.contrib.loader.processor import TakeFirst, MapCompose

class YourItemLoader(XPathItemLoader):
    default_item_class = YourItemClass

    default_input_processor = MapCompose(unicode.strip)
    default_output_processor = TakeFirst()

    # title_in = MapCompose(unicode.strip)

并以这种方式加载项目:

def parse(self, response):
    hxs = HtmlXPathSelector(response)

    for title in hxs.select("//tr/td"):
        loader = YourItemLoader(selector=title, response=response)
        loader.add_xpath('title', 'h3/a/text()')

        yield loader.load_item()
于 2013-08-24T06:44:01.377 回答
0

作为替代的简单答案,您可以编写一个这样的辅助函数:

def extractor(xpathselector, selector):
    """
    Helper function that extract info from xpathselector object
    using the selector constrains.
    """
    val = xpathselector.select(selector).extract()
    return val[0] if val else None

并这样称呼它:

item['title'] = extractor(titles, 'h3/a/text()')
于 2013-09-26T00:06:28.827 回答