使用Selenium WebDriver在其中查找iFrame和控件

时间:2016-03-14 21:26:19

标签: selenium iframe webdriver

我正在尝试使用Selenium Webdriver自动化www.snapdeal.com。我无法点击iframe中的网络元素,因为我看到Element不可见的异常。

以下是代码段

package com.snapdeal.framework.rough;

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class Lab {

    public static WebDriver browser;
    public static WebElement currentElement;
    public static Actions actions;

    public static void main(String[] args) {
        //System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"//src//main//resources//chromedriver.exe");
        browser = new FirefoxDriver();
        browser.get("http://www.snapdeal.com");
        browser.manage().window().maximize();
        browser.findElement(By.xpath("//*[@id='pincodeSalienceComponent']/div[2]/i")).click();
        actions = new Actions(browser);
        actions.moveToElement(browser.findElement(By.xpath("//*[@id='accountHeader']/div[1]"))).perform();
        actions.moveToElement(browser.findElement(By.xpath("//*[@id='accountHeader']/div[2]/div[2]/div[1]/p/span[2]"))).click().build().perform();
        //By executing a java script
        JavascriptExecutor exe = (JavascriptExecutor) browser;
        Integer numberOfFrames = Integer.parseInt(exe.executeScript("return window.length").toString());
        System.out.println("Number of iframes on the page are " + numberOfFrames);

        //By finding all the web elements using iframe tag
        List<WebElement> iframeElements = browser.findElements(By.tagName("iframe"));
        System.out.println(iframeElements.get(0));
        System.out.println("The total number of iframes are " + iframeElements.size());

        try{
            browser.switchTo().frame(1);
        }catch(Exception e){
            System.out.println(e.getMessage());
        }

        try{
            browser.findElement(By.xpath("//*[@id='login-register-modal']/div[2]/div[2]/div[2]/div")).click();
        }catch(Exception e){
            System.out.println(e.getMessage());
        }

        browser.close();
    }

}

你能指导我如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您需要switch to iframe

// click Mobile number and email button first an then
driver.switchTo().frame("loginIframe");
// after registration is done switch back to top frame:
driver.switchTo().defaultContent();