有时候我们在定位一个页面元素的时候发现一直定位不了,反复检查自己写的定位器没有任何问题,代码也没有任何问题。这时你就要看一下这个页面元素是否在一个iframe中,这可能就是找不到的原因之一。
如果你在一个default content中查找一个在iframe中的元素,那肯定是找不到的。反之你在一个iframe中查找另一个iframe元素或default content中的元素,那必然也定位不到。
selenium webdriver中提供了进入一个iframe的方法:
也提供了一个返回default content的方法:
这样使我们面对iframe时可以轻松应对。
switch_to方法会new 1个TargetLocator对象,使用该对象的frame方法可以将当前识别的”主体”移动到需要定位的frame上去。
以下面的html代码为例,我们看一下处现iframe。
这个2个页面放桌面
Html代码
main.html
<html>
<div id = "id1">this is a div!</div>
</html>
frame.html
<html>
<div id = "div2">this is a frame,too!</div>
<label>input:</label>
<input id = "input2" value='frame VALUE'>a frame</input>
</html>
Java代码
package com.test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Test_frame {
public static void main(String[] args) {
String url = "file:///C:/Documents and Settings/fei yong/桌面/main.html";
}
}
页面输出: