码迷,mamicode.com
首页 > Web开发 > 详细

Selenium webdriver定位iframe里面元素

时间:2017-12-08 01:33:36      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:data   drive   bsp   device   money   rod   ice   找不到   use   

在查找元素过程中,直接通过id或者xpath等找不到元素,查看页面源代码发现元素是属于iframe里,例如:

<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种方法:

方法一:单独打开iframe网址,直接定位。

方法二:先切换到iframe,再进行定位。

值得注意的是,如果iframe有id时,切换iframe时把id作为参数直接传入

driver.switch_to.frame("id")

 

以上示例中,iframe没有id,只有class="frame_login",所以我们需要先通过classname定位到iframe元素,再把该元素作为参数传入。

例如,如果要跳出iframe,可以使用以下方法:

# 跳出frame, 进入default content;
driver.switch_to().default_content()

 

1.iFrame有ID 或者 name的情况
进入id="frame1"的frame中,定位id="div1"的div和id="input1"的输入框。

driver.switch_to.frame("frame1");
driver.findElement(By.id("div1"));
driver.findElement(By.id("input1"))

 

2.如果一个iFrame既没有id,也没有name,通用情况
定位frame位置,并选取frame

WebElement frame=driver.findElement(By.xpath( "/html/body/div[2]/div[8]/div[2]/div[3]/div/div[2]/div/iframe" ));
driver.switch_to.frame(frame);

 

3.跳出iFrame
跳出frame,进入default content;重新定位id="id1"的div

driver.switch_to().default_content();
driver.findElement(By.id("id1"))

 

注意:最后只需要退出一次iframe即可

Selenium webdriver定位iframe里面元素

标签:data   drive   bsp   device   money   rod   ice   找不到   use   

原文地址:http://www.cnblogs.com/zhouxinfei/p/8001496.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!