如何根据Selenium的HTML提取跨度内的文本209.520?

时间:2018-08-25 23:41:17

标签: java selenium xpath css-selectors webdriver

我正在使用selenium进行自动化,并且试图获取span标签内的值。我该怎么做?我已经尝试过使用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>

2 个答案:

答案 0 :(得分:1)

根据您共享的HTML,所需的元素是getElementById()元素,因此要提取文本 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");
    

答案 1 :(得分:0)

使用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()')))