我正在尝试从网站获取一些数据,但是当我使用以下代码时,它返回所有匹配的元素,我只想返回第一个匹配项!我试过extract_first,但没有返回!

# -*- 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选择器仅选择一个元素?

最佳答案

这是因为第一个元素实际上是空的-仅过滤掉非空值并使用extract_first()-对我有用:

$ 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.'

关于python - xpath只能选择一个html标签,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39574222/

10-10 11:54