【问题标题】:How to extract the text 209.520 within a span as per the HTML through Selenium?如何通过 Selenium 根据 HTML 提取跨度内的文本 209.520?
【发布时间】:2019-01-31 23:24:17
【问题描述】:

我正在使用 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>

【问题讨论】:

  • 你能提供一个你正在尝试的源代码的例子吗?
  • 如果必须有多个节点与您的 xpath 匹配。将 HTML 放在这里。
  • 如果此元素放置在不同的 iframe 中,您也可以获得 null。没有你的代码真的很难找到问题。

标签: java selenium xpath css-selectors webdriver


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-06-12
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 2017-11-09
      • 2022-06-11
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多