簡體   English   中英

Scrapy導出無效的json

[英]Scrapy exports invalid json

我的解析看起來像這樣:

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"]}]

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

作為一個替代的簡單答案,你可以編寫一個這樣的輔助函數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM