以下是我的代码: -
as
我想要做的是,使用for循环迭代每个帧并找到我需要的元素。
但是,我能够找到第一个元素,即package Practice;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Day6FramesRecap {
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com/recaptcha/api2/demo");
int framenumber = frameset(driver,By.xpath(".//*[@id='recaptcha-anchor']/div[5]"));
driver.switchTo().frame(framenumber);
driver.findElement(By.xpath(".//*[@id='recaptcha-anchor']/div[5]")).click();
driver.switchTo().defaultContent();
try{
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
int framenumber2 = frameset(driver,By.xpath(".//*[@id='recaptcha-verify-button']"));
driver.switchTo().frame(framenumber2);
driver.findElement(By.xpath(".//*[@id='recaptcha-verify-button']")).click();
}
public static int frameset(WebDriver driver, By by)
{
int i;
int framecount= driver.findElements(By.tagName("iframe")).size();
for(i=0;i<framecount;i++)
{
driver.switchTo().frame(i);
int count = driver.findElements(by).size();
if(count>0)
{
break;
}
else
{
System.out.println("Continue Looping");
}
}
driver.switchTo().defaultContent();
return i;
}
}
,点击后,我无法点击第二个元素By.xpath(".//*[@id='recaptcha-anchor']/div[5]
我遇到一个错误,说明: -
线程“main”中的异常 org.openqa.selenium.NoSuchElementException:无法找到 元件: { “方法”: “的xpath”, “选择器”: “.//*[@ ID = '的reCAPTCHA - 验证键']”}
答案 0 :(得分:1)
您可以使用WebElements在iframe之间切换。 您可以尝试以下代码,
public static void main(String args[]) throws InterruptedException
{
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com/recaptcha/api2/demo");
WebElement frame = driver.findElement(By.xpath(".//iframe[@title='recaptcha widget']"));
driver.switchTo().frame(frame);
driver.findElement(By.xpath(".//*[@id='recaptcha-anchor']/div[5]")).click();
driver.switchTo().defaultContent();
Thread.sleep(2000);
WebElement frame1 = driver.findElement(By.xpath(".//iframe[@title='recaptcha challenge']"));
driver.switchTo().frame(frame1);
driver.findElement(By.xpath(".//*[@id='recaptcha-verify-button']")).click(); // this will click on the [Verify] button.
}