【问题标题】:How to click the alert only if it is displayed in Browser Selenium java?仅当它显示在浏览器 Selenium java 中时如何单击警报?
【发布时间】:2018-09-18 12:36:38
【问题描述】:

这里是测试场景

  • 第 1 步:- 输入用户名和密码
  • 第 2 步:- 如果用户已经登录,将出现警报/弹出窗口 带有注销链接,然后单击注销链接并尝试登录 再次。

这是该警报的 HTML 代码

<div class="top-alert hidden-xs hidden-sm">
    <div id="alert0" class="alert pull-right alert-danger alert-dismissable" style="display:none;">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
        <strong>Error:</strong> Invalid Inputs!
    </div>
    <div id="alert2" class="alert pull-right alert-warning alert-dismissable" style="display:none;">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
        <strong>Warning:</strong> Your Login is limited
    </div>
    <div id="alert3" class="alert pull-right alert-warning alert-dismissable" style="display:none;">
        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
        <strong>Warning:</strong> You are Already Loggedin <a href="http://localhost/myapp/public/logout">Logout</a>
    </div>
</div>

这里是网站screenshot

这是我的解决方案

public class Test
{
    public static void main(String[] args)
    {
        System.setProperty("webdriver.chrome.driver", "C:\\\\Selenium\\\\drivers\\\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://localhost/myapp/public/login");

        // Maxmimize windows
        driver.manage().window().maximize();

        // Login the Tripmaker
        driver.findElement(By.xpath("//input[@id='email']")).sendKeys("test@test.com");
        driver.findElement(By.id("password")).sendKeys("s123456");
        driver.findElement(By.cssSelector("#lsbt")).click();

        // Explicit wait
        if (!driver.findElement(By.xpath("//div[@class='top-alert hidden-xs hidden-sm']/div[@id='alert3']/a[contains(text(), 'Logout')]")).isDisplayed())
        {
            WebDriverWait alert = new WebDriverWait(driver, 5);
            alert.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='top-alert hidden-xs hidden-sm']/div[@id='alert3']/a[contains(text(), 'Logout')]")));
            driver.findElement(By.xpath("//div[@class='top-alert hidden-xs hidden-sm']/div[@id='alert3']/a[contains(text(), 'Logout')]")).click();
        }
        else if (driver.findElement(By.xpath("//div[@class='top-alert hidden-xs hidden-sm']/div[@id='alert3']/a[contains(text(), 'Logout')]")).isDisplayed()) 
        {           
            System.out.println("This step is skipped");
        }
    }
}

我的代码正在运行,但如果在登录时显示警报,则会引发错误

Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.xpath: //div[@class='top-alert hidden-xs hidden-sm']/div[@id='alert3']/a[contains(text(), 'Logout')] (tried for 5 second(s) with 500 milliseconds interval)
  at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:113)
  at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:283)
  at demo.myapp.main(myapp.java:41)
Caused by: org.openqa.selenium.NoSuchElementException: Cannot locate an element using By.xpath: //div[@class='top-alert hidden-xs hidden-sm']/div[@id='alert3']/a[contains(text(), 'Logout')]

我试过.isDisplayed().isSelected().isEnabled ()

【问题讨论】:

  • 首先,我强烈建议您看一下 Page-Object-Model。这使得代码更具可读性和可维护性。至于你的问题:只是通过类名猜测:一旦显示警报,具有类“top-alert”的 DIV 是否可能会更改类“hidden-xs”和“hidden-sm”?
  • @JeffC 请不要将&lt;blockquote&gt; 添加到错误跟踪日志中,因为错误跟踪日志会被截断并且几乎不可能调试错误跟踪日志。
  • @Newcontributor 我从未见过有人因为使用 blockquote 而被截断,而且我已经引用过或看到过一些非常非常大的引号。我确认这个也没有被截断。你有一个被截断的例子吗?
  • @JeffC 我之前使用了错误的术语。而不是 truncated 读取为 日志被包装。我坚信现在这个例子几乎是不言自明的。

标签: java selenium-webdriver


【解决方案1】:

根据您的用例,等待警报出现注销链接,然后单击文本为注销的链接,您需要诱导 WebDriverWait 使 元素可点击,您可以使用以下代码块:

//Login the Tripmaker
driver.findElement(By.xpath("//input[@id='email']")).sendKeys("test@test.com");
driver.findElement(By.id("password")).sendKeys("s123456");
driver.findElement(By.cssSelector("#lsbt")).click();
try {
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='top-alert hidden-xs hidden-sm']//div[@class='alert pull-right alert-warning alert-dismissable' and @id='alert3']//a[@href='http://localhost/myapp/public/logout']"))).click();
}
catch (TimeoutException e) { 
    System.out.println("Element is not present");
}

【讨论】:

    【解决方案2】:

    你可以像这样通过 try-catch 块来处理弹出窗口,

    try {
          if(driver.findElement(By.id("alert3")).isDisplayed())
          {
          driver.findElement(By.linkText("Logout")).click();
          }
    } catch(Exception e) {
          System.out.println("User defined Message");
    }
    

    【讨论】:

      【解决方案3】:

      我在您的代码中修复了一些问题。您混合了By.id()By.cssSelector()By.XPath(),所有查找元素都有 ID。您应该首选可用的 ID 并使用 By.id()。您还有很多不必要的额外ifs。您检查了该元素是否不可见,然后等待它可见,然后再次找到它并单击它,否则如果它不可见则打印一条消息。总而言之,当您只需要做一次时,您最终会找到该元素 4 次。

      由于该元素可能存在也可能不存在,我们需要等待它,因此您需要用 try-catch 包围等待。

      public class Test
      {
          public static void main(String[] args)
          {
              System.setProperty("webdriver.chrome.driver", "C:\\\\Selenium\\\\drivers\\\\chromedriver.exe");
              WebDriver driver = new ChromeDriver();
              driver.get("http://localhost/myapp/public/login");
      
              // Maxmimize windows
              driver.manage().window().maximize();
      
              // Login the Tripmaker
              driver.findElement(By.id("email")).sendKeys("test@test.com");
              driver.findElement(By.id("password")).sendKeys("s123456");
              driver.findElement(By.id("lsbt")).click();
      
              try
              {
                  // wait for the logout link in the dialog and click it
                  new WebDriverWait(driver, 3).until(ExpectedConditions.elementToBeClickable(By.cssSelector("#alert3 a[href$='logout']"))).click();
              }
              catch (TimeoutException)
              {
                  // logout link was never displayed
                  System.out.println("This step is skipped");
              }
          }
      }
      

      【讨论】:

      • 显示此错误语法错误,插入“VariableDeclaratorId”完成FormalParameter
      • this。你的项目有问题。
      猜你喜欢
      • 2023-02-05
      • 2023-03-07
      • 1970-01-01
      • 2016-08-10
      • 2019-12-24
      • 2023-02-06
      • 1970-01-01
      • 2018-11-09
      • 2011-11-15
      相关资源
      最近更新 更多