java 如何处理selenium中的java脚本弹出框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15608778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:15:30  来源:igfitidea点击:

How to handle java script pop up box in selenium

javaseleniumwebdrivertestng

提问by sarmila

I created an automation script for login which contains username and password.

我创建了一个用于登录的自动化脚本,其中包含用户名和密码。

I have an excel sheet in which the result is updated as pass if the username and password is correct.

我有一个 Excel 工作表,如果用户名和密码正确,结果将更新为通过。

But if the username and password is incorrect one JavaScript pop up box is coming.

但是如果用户名和密码不正确,就会出现一个 JavaScript 弹出框。

I am unable to handle that ok button.

我无法处理那个确定按钮。

I already tried this code. But I am getting Exception

我已经试过这段代码了。但我得到异常

org.openqa.selenium.WebDriverException: findElement execution failed;
 An open modal dialog blocked the operation 
(WARNING: The server did not provide any stacktrace information).

How to handle open modal dialog box?

如何处理打开的模态对话框?

Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();

Here is my code

这是我的代码

public class Read {

    public WebDriver driver;

    @BeforeMethod
    public void launch() throws Exception {
        System.setProperty("webdriver.chrome.driver",
                "C:\Chrome\chromedriver_win_26.0.1383.0\chromedriver.exe");
        driver = new ChromeDriver();
    }

    @Test
    public void testImportexport1() throws BiffException, IOException,
            RowsExceededException, WriteException, InterruptedException {

        FileInputStream fis = new FileInputStream("Data//Logindev.xls");
        Workbook w = Workbook.getWorkbook(fis);
        Sheet s = w.getSheet(0);
        String a[][] = new String[s.getRows()][s.getColumns()];

        FileOutputStream fos = new FileOutputStream("Data//Logindev_1.xls");
        WritableWorkbook wwb = Workbook.createWorkbook(fos);
        WritableSheet ws = wwb.createSheet("LoginResult", 0);

        System.out.println("s.getRows() = " + s.getRows());

        for (int i = 0; i < s.getRows(); i++) {
            System.out.println("s.getColumns() = " + s.getColumns());

            for (int j = 0; j < s.getColumns(); j++) {
                a[i][j] = s.getCell(j, i).getContents();
                Label l = new Label(j, i, a[i][j]);
                Label l1 = new Label(2, 0, "Result");

                ws.addCell(l);
                ws.addCell(l1);

                System.out.println("Labels Added!!!!!!!!!");
            }
        }
        for (int i = 1; i < s.getRows(); i++) {
            driver.get("any url");

            driver.findElement(By.name("txtUserName")).sendKeys(
                    s.getCell(0, i).getContents());
            driver.findElement(By.name("txtPwd")).sendKeys(
                    s.getCell(1, i).getContents());
            driver.findElement(By.name("btnSignIn")).click();

            Thread.sleep(15000);

            if (driver.findElement(By.linkText("xyz")).isDisplayed()) {
                System.out.println("Element is found");
                driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                driver.findElement(
                        By.xpath("//*[@id='ctl00_headerContent_lnkLogOut']"))
                        .click();
                Thread.sleep(2000);
                Label l2 = new Label(2, i, "Pass");
                ws.addCell(l2);
            } else {

                try {
                    System.out.println("Element Not Found");
                    Label l2 = new Label(2, i, "Fail");
                    ws.addCell(l2);
                    Alert alert = driver.switchTo().alert();
                    System.out.println(alert.getText());
                    alert.accept();
                } catch (NoAlertPresentException e) {
                    e.printStackTrace();
                }

            }
        }
        Thread.sleep(2000);
        wwb.write();
        wwb.close();
    }

}

回答by CheryJose

I think your code snippet to handle a modal dialog box is correct. I even tried it in c# format for a website it works.

我认为您处理模式对话框的代码片段是正确的。我什至在它工作的网站上以 c# 格式尝试过它。

IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.tizag.com/javascriptT/javascriptalert.php");
driver.FindElement(By.XPath("//div/form/input[@value='Confirmation Alert']")).Click();
IAlert alert = driver.SwitchTo().Alert();
Console.WriteLine(alert.Text);
alert.Accept();

What I think wrong in your case is that may be your alert handling code is not immediately after the code line which triggers the modal dialog. From the error message you have given it is evident that you are doing some operation on the web page after the modal dialog is displayed and before handling it.

我认为在您的情况下错误的是,您的警报处理代码可能不是在触发模态对话框的代码行之后立即执行的。从您给出的错误消息中可以明显看出,您正在显示模态对话框之后和处理它之前在网页上进行一些操作。

org.openqa.selenium.WebDriverException: findElement execution failed;
An open modal dialog blocked the operation 

I also want to mention about another method to suppress modal dialogs in c# way. Use SendKeysclass of name space System.Windows.Formsand send keyboard entries directly like,

我还想提到另一种以 c# 方式抑制模态对话框的方法。使用名称空间System.Windows.Forms 的SendKeys类并直接发送键盘条目,例如,

IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.tizag.com/javascriptT/javascriptalert.php");
driver.FindElement(By.XPath("//div/form/input[@value='Confirmation Alert']")).Click();
SendKeys.SendWait("{Enter}");


Update

更新



driver.findElement(By.name("txtUserName")).sendKeys(s.getCell(0, i).getContents());
driver.findElement(By.name("txtPwd")).sendKeys(s.getCell(1, i).getContents());
driver.findElement(By.name("btnSignIn")).click();
try{
    Alert alert = driver.switchTo().alert();
    System.out.println(alert.getText());
    alert.accept();
   }
catch (NoAlertPresentException e) {

      if (driver.findElement(By.linkText("xyz")).isDisplayed()) 
        {
         System.out.println("Element is found");
         driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
         driver.findElement(
         By.xpath("//*[@id='ctl00_headerContent_lnkLogOut']")).click();
         Thread.sleep(2000);
         Label l2 = new Label(2, i, "Pass");
         ws.addCell(l2);
        } 
     else 
        {
         System.out.println("Element Not Found");
         Label l2 = new Label(2, i, "Fail");
         ws.addCell(l2);
         } 
      }

回答by Code Enthusiastic

You need to check for the presence of an alertafter pressing the logIn button.

您需要在按下登录按钮后检查是否存在警报

driver.findElement(By.id("logIn")).click();

isAlertPresent();


public void isAlertPresent();  
{
    try
    {
        Alert alert = driver.switchTo ().alert ();
        //alert is present
        System.out.println(alert.getText());
        alert.accept(); 
    }
    catch ( NoAlertPresentExceptionn n)
    {
        //Alert isn't present
        return; 
    }
}

回答by Hemanth

I cannot give exact solution, but the following approach may help you.

我无法给出确切的解决方案,但以下方法可能会对您有所帮助。

//method for checking if Alert is present.

//用于检查警报是否存在的方法。

public boolean isAlertPresent() 
{ 
    try 
    { 
        driver.switchTo().alert(); 
        return true; 
    }   // try 
    catch (NoAlertPresentException Ex) 
    { 
        return false; 
    }   // catch 
} 

//entering username and password

//输入用户名和密码

         //click on Login Button
         if( logout button is displayed )
         {
             //click logout
         }
         else if(isAlertPresent())//we are calling the above mentioned isAlertpresent method where, if it returns true, the below code gets executed.
         {
           alert.accept(); 
           Label l2 = new Label(2, i, "Fail");
           ws.addCell(l2);

         }
    }

Hope it gives some idea. Let us know if you are still facing the issue.

希望它提供一些想法。如果您仍然面临此问题,请告诉我们。