如何通过硒根据 HTML 在一个范围内提取文本 209.520?



我正在用硒进行自动化,我正在尝试获取跨度标签内的值。我该怎么做?我已经尝试过使用 getText(( 但打印了一个空

这是 HTML 中的行

<span class="visible-xs" data-bind="html: PriceWithoutCurrencySymbol">209.520</span>

我需要取数字 99.520。我已经制作了找到它的正确 xpath,但我如何提取该值?

感谢您的帮助。

xpath 如果它带来了几个对象,但我需要的是获取该值,

这是我使用的 XPath

//div[@class='totalPrice']/span[@data-bind='html: PriceWithoutCurrencySymbol']

这是代码 HTML

<div class="flightPriceContainer notranslate">
<div class="totalPrice">
<span class="hidden-xs" data-bind="html: Price">COP 209.520</span>
<span class="visible-xs" data-bind="html: CurrencySymbol">COP</span>
<span class="visible-xs" data-bind="html: PriceWithoutCurrencySymbol">209.520</span>
</div>
</div>

根据您共享的 HTML 所需元素是 React 元素,因此要提取文本209.520,您必须诱导WebDriverWait元素可见,您可以使用以下任一解决方案:

  • cssSelector

    String labelText = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.flightPriceContainer.notranslate > div.totalPrice > span.visible-xs[data-bind$='PriceWithoutCurrencySymbol']"))).getAttribute("innerHTML");
    
  • xpath

    String labelText = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='flightPriceContainer notranslate']/div[@class='totalPrice']/span[@class='visible-xs' and contains(@data-bind,'PriceWithoutCurrencySymbol')]"))).getAttribute("innerHTML");
    

使用 lxml 的 Python 解决方案,但 xpath 在 Java 中应该是相同的。

html = '<span class="visible-xs" data-bind="html: PriceWithoutCurrencySymbol">99.520</span>'
print(''.join(lxml.html.fromstring(html).xpath('//span//text()')))

最新更新