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 に答える