【问题标题】:Unable to locate nested text using XPath无法使用 XPath 定位嵌套文本
【发布时间】:2021-04-07 01:32:20
【问题描述】:

我是自动化新手,正在尝试测试一次失败的登录。输入错误密码时,网站上会显示错误弹出窗口。我正在尝试编写测试以确认显示错误文本。

代码试验:

@Test
    public void IncorrectPasswordMessage() {

        boolean b=driver.findElement(By.xpath("//*[@id=\"errors\"]/h2")).isDisplayed();
        Assert.assertTrue(b);

    }

HTML 如下。如何更改我的脚本以确认嵌套文本“有以下错误。” 显示在网页上?

<form id="login_form" action="/cs/form/customer-login" method="AJAX" class="cforms pad-top1 span6">
    <!--|cid=1400679170853|type=Forms_P|-->
    <div id="errors" style="">
        <h2>There are the following errors.</h2>
        <ul><li>The number and password you have entered do not match. Please enter it again.</li></ul>
    </div>
    <input type="hidden" name="_form_url" value="">
    <input type="hidden" name="_success_url" value="">
    <input type="hidden" name="_failure_url" value="">
</form>

【问题讨论】:

  • 根据您的Assert.assertTrue(),我已将javascript 标签替换为java 标签。如果更改看起来不错,请告诉我。

标签: java selenium xpath css-selectors webdriverwait


【解决方案1】:

该元素是AJAX 元素,因此对于click() 元素,您需要将WebDriverWait 诱导为visibilityOfElementLocated(),您可以使用以下任一Locator Strategies

  • cssSelector

    @Test
        public void IncorrectPasswordMessage() {
            WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div#errors>h2")));
            // lines of code
            Assert.assertTrue(b);
        }
    
  • xpath

    @Test
        public void IncorrectPasswordMessage() {
            WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='errors']/h2")));
            // lines of code
            Assert.assertTrue(b);
        }
    

【讨论】:

  • 感谢 DebanjanB 的快速响应。我已经尝试了两种定位器策略,但它返回“预期条件失败:等待 By.cssSelector 定位的元素的可见性:div#errors>h2(尝试 20 秒,间隔 500 毫秒)”。添加定位器策略时,eclipse 会突出显示一个错误,指出“类型不匹配:无法从 WebElement 转换为布尔值”,我已经尝试了这两种修复方法。
  • @MichaelD 代码中出现错误,因为visibilityOfElementLocatedExpectedConditions 将始终返回元素,您不能将其视为布尔值。更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-11
  • 2016-07-01
  • 2022-09-24
  • 1970-01-01
  • 2020-04-19
  • 1970-01-01
相关资源
最近更新 更多