首页 > 解决方案 > 如何通过 Selenium 根据 HTML 提取跨度内的文本 209.520?

问题描述

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

这是 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>

标签: javaseleniumxpathcss-selectorswebdriver

解决方案


根据您共享的 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");
    

推荐阅读