【问题标题】:How to allocate a value to a specific xpath variable?如何为特定的 xpath 变量分配值?
【发布时间】:2020-02-10 13:12:50
【问题描述】:

我有一个html代码,如下图。

<div class="perc">
  <div class="blc-p">
    <span class="green_r " style="width:75%">75,0%</span>
  </div>
  <div class="blc-p">
    <span class="yellow_r small" style="width:14%"></span>
     14,2%
  </div>
  <div class="blc-p">
    <span class="red_r small" style="width:10%"></span> 
     10,8%
  </div>
</div>

从上面的 html 中,我得到了 class="red_r small" 的 xpath:

red = doc.xpath('.//div[@class="perc"]/div[3]/span[@class="red_r small"]')

我正在尝试根据“perc”类的 div 中的位置为“red”分配一个值,这样:

如果“red”在“blc-p”类的第一个div中,则red的值变为1。 如果“red”在“blc-p”类的第二个 div 中,则 red 的值变为“N”。 如果'red'在“blc-p”类的第三个div中,则red的值为2。

在上面的例子中,red = 2 因为它在“blc-p”类的第三个 div 中。

如何使用 xpath 和 python3 实现这一点? 谢谢

【问题讨论】:

  • 为什么不能简单地指定doc.xpath('.//div[@class="perc"]//span[@class="red_r small"]'),这样无论位置如何,红色都会被拾取。

标签: python-3.x xpath


【解决方案1】:

您可以在序列上使用函数https://www.w3schools.com/xml/xsl_functions.asp#sequence

您的解决方案是这样的,其中 3 是元素的索引:

index-of(//span, //span[contains(@class, "red")])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-13
    相关资源
    最近更新 更多