Selenium webdriver定位iframe里面元素两种方法
以东方财富网登录页面为例:
在查找元素过程中,直接通过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网址,直接定位。
@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(); } }
方法二:先切换到iframe,再进行定位。
@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作为参数直接传入
driver.switchTo().frame("id");
以上示例中,iframe没有id,只有class="frame_login",所以我们需要先通过classname定位到iframe元素,再把该元素作为参数传入。
例如,如果要跳出iframe,可以使用以下方法:
driver.switchTo().defaultContent();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构