【问题标题】:xpath cant select only one html tagxpath 不能只选择一个 html 标签
【发布时间】:2016-09-19 13:18:20
【问题描述】:

我正在尝试从网站获取一些数据,但是当我使用以下代码时,它会返回所有匹配的元素,我只想返回第一个匹配项!我试过 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 选择器只选择一个元素?

【问题讨论】:

    标签: python python-3.x xpath web-scraping scrapy


    【解决方案1】:

    这是因为第一个元素实际上是空的 - 仅过滤掉非空值并使用 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.'
    

    【讨论】:

      【解决方案2】:

      严格来说应该是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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-25
        • 1970-01-01
        • 2017-05-04
        • 2012-01-08
        相关资源
        最近更新 更多