首页 > 解决方案 > 如何比较单击按钮几秒钟后加载的登录页面上的文本?

问题描述

我正在学习 Selenium Webdriver,并且正在编写代码来填写 rediff.com 的注册表单。选择 rediffmail ID 时,有一个验证按钮,用于检查输入的 ID 的可用性,并在所选 ID 可用时给出结果。我想比较该文本,如果 ID 可用,则它会自动填充页面的其余部分,但如果它不可用,则它会停止并显示一条消息以选择新 ID。我能够实现一些代码,但我认为这不是最好的方法,因此请教专家。请建议我在下面包含我的代码。在此先感谢您的帮助。

public void fillformredifflocators() {  
    try {
        invokebrowser("http://register.rediff.com/register/register.php?FormName=user_details");
        driver.findElement(By.xpath("/html/body/center/form/div/table[2]/tbody/tr[3]/td[3]/input")).sendKeys("Rediff User");
        driver.findElement(By.xpath("/html/body/center/form/div/table[2]/tbody/tr[7]/td[3]/input[1]")).sendKeys("abcd540");
        driver.findElement(By.className("btn_checkavail")).click();
        driver.manage().timeouts().pageLoadTimeout(100, TimeUnit.SECONDS);
        String expectedMessage = "Yippie! The ID you've chosen is available.";
        String Message = driver.findElement(By.xpath("//b[contains(text(),\"Yippie! The ID you've chosen is available.\")]")).getText();
        Assert.assertEquals(Message, expectedMessage);
         if (expectedMessage.equals(Message))
             {
             System.out.println("Congrats ! Your chosen id can be used");
             }
             else
             {
             System.out.println("Please use a different id as the chosen id is taken");
             }

        driver.findElement(By.xpath("/html[1]/body[1]/center[1]/form[1]/div[1]/table[2]/tbody[1]/tr[9]/td[3]/input[1]")).sendKeys("password123");
    } catch (Exception e) {

        e.printStackTrace();
    }
}

标签: javascriptvalidationselenium-webdriver

解决方案


欢迎来到 SO。

您必须改进脚本中使用的定位器。尝试使用相对 xpath 而不是绝对 xpath。而且您不必存储消息然后在此处比较验证。只需检查是否Yippie! The ID you've chosen is available.存在带有文本的元素,它本身是否可以被视为验证。

if (driver.findElements(By.xpath("//b[contains(text(),\"Yippie! The ID you've chosen is available.\")]")).size()>0){
    System.out.println("Congrats ! Your chosen id can be used");
}else{
    System.out.println("Please use a different id as the chosen id is taken");
}

推荐阅读