【问题标题】:Scrapy: how to fetch information that comes after some specific text?Scrapy:如何获取某些特定文本之后的信息?
【发布时间】:2017-07-08 17:00:40
【问题描述】:

我正在使用 Scrapy 获取我所在地区的公寓价格。在广告描述中,有一个带有属性的列表,如下所示:

<ul class="list">
  <li class="item">Size: <strong class="description">100 m²</strong></li>
  <li class="item">Rooms: <strong class="description">3</strong></li>
  <li class="item">Parking space: <strong class="description">2</strong></li>
  <li class="item">Annual taxes: <strong class="description">$ 1000</strong></li>
</ul>

我遇到的问题是,其中一些属性(例如年税和停车位)并未出现在所有广告中。这意味着我不能简单地使用 extract() 和 #-index 来获取该信息,因为我可能会捕获错误类别的信息。

所以我的问题是:如何获取紧跟在“年税”或“停车位”文本之后的信息? XPath 或 RegEx 可以做到这一点吗?

这是我目前用于蜘蛛的代码:

import scrapy

class ExampleSpider(scrapy.Spider):
    name = 'example'

    start_urls = ['http://www.example.com']

    def parse(self, response):
        for item in response.css('li.item'):
            url = item.css('a.link::attr(href)').extract_first()
            yield scrapy.Request(url, callback=self.parse_item)

    def parse_item(self, response):
        title = response.css('h1.ad-title::text').extract_first().strip()
        price = response.css('span.ad-price::text').extract_first()
        size = response.css('li.item strong.description::text').extract()[0].strip(' m²')
        rooms = response.css('li.item strong.description::text').extract()[1]
        parking = response.css('li.item strong.description::text').extract()[2] 
        taxes = response.css('li.item strong.description::text').extract()[3]

【问题讨论】:

    标签: python regex xpath web-scraping scrapy


    【解决方案1】:

    顺便说一句,我假设你错过了关闭 strong 标签

    response.xpath('//li[@class="item" and contains(.,"Annual taxes:")]/strong/text()')
    

    【讨论】:

    • 效果很好!谢谢你,小伙伴!另外,我关闭了 标签。
    猜你喜欢
    • 1970-01-01
    • 2023-04-06
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    相关资源
    最近更新 更多