简体   繁体   中英

Scrapy exports invalid json

My parse looks like this:

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

Why does it output json like this:

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

titles.select('h3/a/text()').extract() returns a list, so you get a list. Scrapy doesn't make any assumptions about your item's structure.

The quick fix would be to just get the first result:

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

A better solution would be to use an item loader and use TakeFirst() as an output processor:

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)

And load the item that way:

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()

As an alternative simple answer you can write a helper function like this:

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

and call it like this:

item['title'] = extractor(titles, 'h3/a/text()')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM