selenium+iframe 如何定位元素(实战)
场景: 在同一界面,需定位iframe里面的元素, 就需要切换至Iframe块,然后定位元素,验证完成后,再切换出来。 如果不切换至iframe ,会发现不管采取什么定位,都会报元素不存在。
2.脚本示例:
@Then("^verify modify payRollData only (.+)$") public void verify_modify_payRollData_only(String staffNo) throws Throwable { pr.verifyPayRollDataOnly(staffNo); }
/** * 验证本期工资单雇员数据只有一条信息 * @param data * @throws Exception */ public void verifyPayRollDataOnly(String staffNo) throws Exception { Utils.waitABit(10000); waitLoading(); String frameElement="SalaryViewer1_Splitter_Viewer_ContentFrame"; driver.switchTo().frame(frameElement); //切进 waitLoading(); String actualStaffNo = waitFor(By.xpath(".//*[text()='" + staffNo + "']")).getText().trim(); Assert.isEqual(staffNo, actualStaffNo); driver.switchTo().defaultContent(); 、、切出 }
3.注意事项:查看iframe 块,可以通过切换DoM查看, 千万不要用手敲,易出错,定位元素也是同样的道理! 切记,切记,勿采坑。
方法二: 前面介绍的直接能切换是因为Iframe有唯一的id.
现在将切换Iframe编写为公共方法
1 /** 2 * 3 * @param xpath 4 * @return 5 * @throws Exception 6 */ 7 public static String switchIframe(String xpath) throws Exception{ 8 WebElement frame = driver.findElement(By.xpath(""+xpath+"")); 9 driver.switchTo().frame(frame); 10 Thread.sleep(2000); 11 return xpath; 12 }
switchIframe("html/body/table/tbody/tr[2]/td");