您的元素在iframe 中。您必须先切换到它才能找到元素:
WebElement iframe = driver.findElement(By.xpath("//iframe"));
driver.switchTo().frame(iframe);
然后你可以像往常一样找到你的元素:
WebElement firstName = driver.findElement(By.xpath("//*[@id='firstNameId']"));
WebElement lastName = driver.findElement(By.xpath("//*[@id='lastNameId']"));
在您处理完iframe 中的内容后,您必须像这样切换回默认内容:
driver.switchTo().defaultContent();
PS: 我也会像这样使用WebDriverWait:
WebDriver driver = new ChromeDriver();
driver.get("https://www.icicibank.com/Personal-Banking/loans/personal-loan/index.page");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='myDivAdd']/a[2]"))).click(); // dismiss popup
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe"))); // switch to iframe
WebElement firstName = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='firstNameId']")));
firstName.click();
firstName.sendKeys("first name");
WebElement lastName = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id='lastNameId']")));
lastName.click();
lastName.sendKeys("last name");
driver.switchTo().defaultContent();
WebDriverWait 将等待至少 10 秒,直到满足 ExpectedConditions 的要求,然后才执行操作。
注意:您必须添加一些导入:
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.By;
更多关于WebDriverWait的信息可以在documentation找到。