【问题标题】:XPath for span and div跨度和 div 的 XPath
【发布时间】:2018-08-22 12:08:55
【问题描述】:
<div id="buyNewSection" class="rbbHeader dp-accordion-row">
<h5>
<div class="a-row">
    <div class="a-column a-span4 a-text-left a-nowrap">
        <span class="a-text-bold">Buy New</span>
    </div>
    <div class="a-column a-span8 a-text-right a-span-last">
        <div class="inlineBlock-display">
            <span class="a-letter-space"></span>
            <span class="a-size-medium a-color-price offer-price a-text-normal">$13.00</span>
        </div>
    </div>
</div>
</h5>

请帮助我们如何使用 XPATH 提取 13 美元的价格?

另外,如果 div id 不存在,那么 XPATH 会是什么?

我正在尝试使用 python 进行抓取。感谢任何帮助。

【问题讨论】:

  • 最后错误地丢失了。
  • 分享你当前的 XPath
  • 这个//span[contains(@class, 'offer-price')]怎么样
  • 标签: python xml parsing xpath lxml


    【解决方案1】:

    使用lxml进行解析:

    from lxml import html
    
    doc = html.fromstring(raw_html)
    doc.xpath('//span[contains(@class,"offer-price")]')[0].text
    

    返回:'$13.00'

    xpath 部分只是查找所有跨度://span 并过滤这些跨度以获取某个类标记 [contains(@class,"offer-price")]

    【讨论】:

    • 或者//span[contains(concat(" ",@class," ")," offer-price ")],所以任何其他类(如offer-prices)都不会意外匹配。
    • 是的,如果这个类有一个跨度,它会导致误报匹配,但这可以通过简单地在“offer-price”周围添加空格来解决,而不会产生任何其他并发症。顺便说一句:我怀疑任何具有“offer-prices”类的元素也将是一个跨度,而不是一个列表或表格。
    【解决方案2】:
    //span[@class = 'a-size-medium a-color-price offer-price a-text-normal']
    

    【讨论】:

    • 请注意,某些类名可能是动态添加的,因此按完整的类名集搜索可能会返回不需要的输出
    • 嗯,答案实际上是基于提供的这些html代码,例如,如果有三个相同的代码,OP可以使用(//span[@class = 'a-size-medium a-color-price offer-price a-text-normal'])[1],如果他想获得中心或只是使用XPATH 轴作为替代。
    • 我认为@Andersson 所说的是试图检查整个“类”属性值是否匹配可能是脆弱的。如果类的顺序发生变化会发生什么?或者添加(或删除)一个新类?
    猜你喜欢
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多