简体   繁体   English

如何处理 Selenium 弹出 java

[英]How to handle the Selenium Pop-up with java

I tried several options to handle the Pop-up with Selenium and fill the field values.我尝试了几个选项来使用 Selenium 处理弹出窗口并填充字段值。 But it does not work with the below code.但它不适用于以下代码。

Selenium java code: Selenium java 代码:

driver.findElement(By.xpath("//*[@id=\"loginBox\"]/div[2]/div/div/div[1]/div")).click();
Thread.sleep(2000);

Alert alert = driver.switchTo().alert();
Thread.sleep(3000);

driver.findElement(By.name("Email")).sendKeys("xxx@yyy.com");
Thread.sleep(2000);

alert.accept();

HTML: HTML:

<div class="content">
 <form class="ui form">
  <div class="field">
   <label for="Email">Email</label>
    <div view="horizontal" class="ui right corner labeled input">
     <div class="ui label label right corner">
      <i aria-hidden="true" class="asterisk icon">
      </i>
     </div><input name="Email" id="Email" placeholder="Please enter email address" type="email" value="">
    </div>
   </div>
  • How can I handle the Pop-up and fill the field?如何处理弹出窗口并填写字段?
  • Also, in the end how do I close the alert window?另外,到底如何关闭警报 window?

The pop-up is HTML element, not a modal dialog to use driver.switchTo().alert() .弹出窗口是 HTML 元素,而不是使用driver.switchTo().alert()的模式对话框。
To enter email you have to wait for the element, and for that sleep bad choice.要输入 email 您必须等待元素,并且等待sleep不好的选择。 Code below waiting for visibility of the email using WebDriverWait , it's best practice.下面的代码使用WebDriverWait等待email的可见性,这是最佳实践。
Also, not a good practice to use //*[@id=\"loginBox\"]/div[2]/div/div/div[1]/div like selectors.此外,像选择器一样使用//*[@id=\"loginBox\"]/div[2]/div/div/div[1]/div不是一个好习惯。 You can find some helpful information about best practice for selectors here .您可以在此处找到有关选择器最佳实践的一些有用信息。

import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

// ...

WebDriverWait wait = new WebDriverWait(driver, 10);

driver.findElement(By.xpath("//*[@id=\"loginBox\"]/div[2]/div/div/div[1]/div")).click();

WebElement email = wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("Email")));
email.sendKeys("xxx@yyy.com");
email.submit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM