以東方財富網登陸頁面爲例:web
在查找元素過程當中,直接經過id或者xpath等找不到元素,查看頁面源代碼發現元素是屬於iframe裏,例如:dom
<div class="wrap_login"> <iframe class="frame_login" src="https://exaccount.eastmoney.com/home/login?request=%7b%22agentPageUrl%22%3a%22https%3a%2f%2fpassport.eastmoney.com%2fpub%2fLoginAgent%22%2c%22redirectUrl%22%3a%22http%3a%2f%2fwww.eastmoney.com%2f%22%2c%22callBack%22%3a%22LoginCallBack%22%2c%22redirectFunc%22%3a%22PageRedirect%22%2c%22data%22%3a%7b%22domainName%22%3a%22passport.eastmoney.com%22%2c%22deviceType%22%3a%22Web%22%2c%22productType%22%3a%22UserPassport%22%2c%22versionId%22%3a%220.0.1%22%7d%7d"></iframe> </div>
如下爲了定位到iframe裏面元素,有2種方法:url
@Test public void loginTest() throws InterruptedException { System.setProperty("webdriver.firefox.bin", "D:\\Program Files\\Mozilla Firefox\\firefox.exe"); WebDriver driver = new FirefoxDriver(); driver.get("https://exaccount.eastmoney.com/home/login?request=%7b%22agentPageUrl%22%3a%22https%3a%2f%2fpassport.eastmoney.com%2fpub%2fLoginAgent%22%2c%22redirectUrl%22%3a%22http%3a%2f%2fwww.eastmoney.com%2f%22%2c%22callBack%22%3a%22LoginCallBack%22%2c%22redirectFunc%22%3a%22PageRedirect%22%2c%22data%22%3a%7b%22domainName%22%3a%22passport.eastmoney.com%22%2c%22deviceType%22%3a%22Web%22%2c%22productType%22%3a%22UserPassport%22%2c%22versionId%22%3a%220.0.1%22%7d%7d"); driver.manage().window().maximize(); Thread.sleep(3000); driver.findElement(By.id("txt_account")).sendKeys("ycyzharry"); driver.findElement(By.id("txt_pwd")).sendKeys("password"); driver.findElement(By.id("btn_login")).click(); } }
@Test public void clickButtonTest() throws InterruptedException { System.setProperty("webdriver.firefox.bin", "D:\\Program Files\\Mozilla Firefox\\firefox.exe"); WebDriver driver = new FirefoxDriver(); driver.get("https://passport.eastmoney.com/pub/login?backurl=http%3A//www.eastmoney.com/"); driver.manage().window().maximize(); Thread.sleep(3000); WebElement iframe = driver.findElement(By.className("frame_login")); driver.switchTo().frame(iframe); driver.findElement(By.id("txt_account")).sendKeys("ycyzharry"); driver.findElement(By.id("txt_pwd")).sendKeys("password"); driver.findElement(By.id("btn_login")).click();
}
}
值得注意的是,若是iframe有id時,切換iframe時把id做爲參數直接傳入spa
driver.switchTo().frame("id");
以上示例中,iframe沒有id,只有class="frame_login",因此咱們須要先經過classname定位到iframe元素,再把該元素做爲參數傳入。firefox
例如,若是要跳出iframe,能夠使用如下方法:3d
driver.switchTo().defaultContent();