日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

Selenium webdriver定位iframe里面元素两种方法

發(fā)布時(shí)間:2024/9/20 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Selenium webdriver定位iframe里面元素两种方法 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

以東方財(cái)富網(wǎng)登錄頁(yè)面為例:

在查找元素過(guò)程中,直接通過(guò)id或者xpath等找不到元素,查看頁(yè)面源代碼發(fā)現(xiàn)元素是屬于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種方法:

方法一:單獨(dú)打開(kāi)iframe網(wǎng)址,直接定位。

@Testpublic 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,再進(jìn)行定位。

@Testpublic 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時(shí),切換iframe時(shí)把id作為參數(shù)直接傳入

driver.switchTo().frame("id");

以上示例中,iframe沒(méi)有id,只有class="frame_login",所以我們需要先通過(guò)classname定位到iframe元素,再把該元素作為參數(shù)傳入。

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

driver.switchTo().defaultContent();

總結(jié)

以上是生活随笔為你收集整理的Selenium webdriver定位iframe里面元素两种方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。