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



我正在尝试使用Selenium Webdriver自动 www.snapdeal.com。我无法单击 iframe 内的 Web 元素,因为我收到元素不可见异常。

下面是代码片段

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();
    }
}

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

你需要切换到 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();

最新更新