无法使用XPath在iframe中查找元素

时间:2019-06-04 06:06:20

标签: google-chrome selenium-webdriver xpath iframe

我正在尝试在网站https://www.toolsqa.com/iframe-practice-page/上的iframe中打印所有锚标签,但是webdriver返回0个元素

我已使用swithcTo方法将控件从主窗口移至iframe,但这没有帮助

driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@id='IF2']")));

@Test
public void iFrmesCount(String browserName) throws InterruptedException {
    if (browserName.equalsIgnoreCase("chrome")) {
        System.setProperty("webdriver.chrome.driver", "drivers//chromedriver.exe");
        driver = new ChromeDriver();}
    driver.get("https://www.toolsqa.com/iframe-practice-page/ ");
    driver.manage().window().maximize();
    Thread.sleep(2000);
    driver.switchTo().frame(driver.findElement(By.xpath("//iframe[@id='IF2']")));
    System.out.println("Span's inside iframe" + driver.findElements(By.xpath(".//span")).size());
    System.out.println("Div's inside iframe" + driver.findElements(By.xpath(".//div")).size());
}   

1 个答案:

答案 0 :(得分:0)

尝试

    driver.get("https://www.toolsqa.com/iframe-practice-page/");
    driver.manage().window().maximize();
    driver.switchTo().frame("IF2");
    List<WebElement> list = driver.findElements(By.tagName("a"));
    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i).getText());
    }