2016-09-19 5 views
1

ウェブサイトからデータを取得しようとしていますが、次のコードを使用すると一致する要素がすべて返されます。私はextract_firstを試しましたが、それは誰も返しませんでした!xpath cantは1つだけのhtmlタグを選択します

# -*- coding: utf-8 -*- 
import scrapy 
from gumtree.items import GumtreeItem 



class FlatSpider(scrapy.Spider): 
    name = "flat" 
    allowed_domains = ["gumtree.com"] 
    start_urls = (
     'https://www.gumtree.com/flats-for-sale', 
    ) 

    def parse(self, response): 
     item = GumtreeItem() 
     item['title'] = response.xpath('//*[@class="listing-title"][1]/text()').extract() 
     return item 

xpathセレクタで1つの要素のみを選択するにはどうすればよいですか?唯一の非空の値をフィルタリングし、extract_first()を使用する - - 最初の要素が実際には空であるため、

答えて

1

これは私の作品:

$ scrapy shell "https://www.gumtree.com/flats-for-sale" -s USER_AGENT="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.113 Safari/537.36" 
In [1]: response.xpath('//*[@class="listing-title"][1]/text()[normalize-space(.)]').extract_first().strip() 
Out[1]: u'REDUCED to sell! Stunning Hove sea view flat.' 
0

を厳密にそれはresponse.xpath('(//*[@class="listing-title"])[1]/text()')あるべき話すが、何を望むのにある場合各広告のタイトルをつかんで(たとえばアイテムを作成するため)、おそらくこれを行うべきです:

for article in response.xpath('//article[@data-q]'): 
    item = GumtreeItem() 
    item['title'] = article.css('.listing-title::text').extract_first() 
    yield item 
関連する問題