【问题标题】:How to access a specific child div using xpath? (Selenium Java)如何使用 xpath 访问特定的子 div? (硒Java)
【发布时间】:2014-12-12 08:34:59
【问题描述】:

我有以下html代码:

<div class="panel">
    <div class = "heading">
        <span class="wName">Name</span>
        <div class="foo1" style="display: none;"></div>
        <div class="foo2" style="display: none;"></div>
    </div>
</div>

我已经找到了元素面板,我正在尝试使用以下代码行测试 foo2 何时不出现:

if (panel.findElement(By.xpath("../div[@class='foo2']")).getCssValue("display").equals("none"))

我不确定为什么不能正确检索元素。

【问题讨论】:

    标签: java selenium xpath selenium-webdriver


    【解决方案1】:

    您的 XPath 错误! .. 表示“父母”。单点. 表示相对于当前位置。

    试试:panel.findElement(By.xpath(".//div[@class='foo2']")

    【讨论】:

    • 或者,您可以使用更简洁的 CSS 解决方案。 @OP。 By.cssSelector("div.foo2")
    • @sircapsalot 如果我们追求“干净”,那么我认为By.className("foo2") 会胜出。
    • 或者我们当然可以走“不太干净”的路线。 By.cssSelector("div[class~='panel']&gt;div[class~='heading']&gt;div[class]:nth-child(3)");)
    • 实际上,由于感兴趣的div不是面板的直接子级,因此XPath需要为.//div[@class='foo2'],或./div/div[@class='foo2'],或./*/div[@class='foo2']等。
    【解决方案2】:

    你用后代怎么样

    panel.findElement(By.xpath("//div[@class='panel']/descendant::div[@class='foo2']"));
    

    来源http://www.caucho.com/resin-3.1/doc/xpath.xtp#descendant

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 2016-06-28
      • 2013-10-10
      • 1970-01-01
      相关资源
      最近更新 更多