selenium学习笔记001

本文介绍了一个使用Selenium和JUnit进行Web应用登录功能自动化测试的例子。测试覆盖了正确的用户名和密码登录场景,并验证了登录后的页面元素。此外,还详细解释了如何处理嵌套的iframe元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.测试点:登录界面,输入正确的用户名、密码,点击登录,进入系统首页

2.代码:

import org.junit.*;
import junit.framework.TestCase;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import static org.junit.Assert.*;

public class LoginTest {
    
 static String url=http://xxx;
 static String element1="webdriver.chrome.driver";
 static String element2="C:/Users/xfr/AppData/Local/Google/Chrome/Application/chromedriver.exe";
 static WebDriver chrome;
 
 WebElement name;
 WebElement pwd;
 
 @BeforeClass
 public static void setUpBeforeClass() throws Exception {
  System.setProperty(element1, element2);
  chrome=new ChromeDriver();
  chrome.get(url);
 }

 @AfterClass
 public static void tearDownAfterClass() throws Exception {
  chrome.close();
}

 
 //点击登陆按钮
 public void clickbtn(){
  WebElement btn = chrome.findElement(By.className("btn_01"));
  btn.click();
 }

 
 //用户名、密码都正确
 @Test
 public void loginSuccess(){
  name = chrome.findElement(By.id("login_name"));
  name.sendKeys("admin");
  pwd = chrome.findElement(By.id("user_pass"));
  pwd.sendKeys("000000");
  clickbtn();

//切换到id为hqFrame的iframe中
  chrome.switchTo().frame("hqFrame");

//找到name为leftFrame的frame
  WebElement frame=chrome.findElement(By.xpath("//frame[@name='leftFrame']"));

//切换到名为leftFrame的frame中
  chrome.switchTo().frame(frame);
  System.out.println(chrome.getPageSource());
  WebElement a=chrome.findElement(By.id("sd1"));
  System.out.println(a.getText());
  assertEquals("首页",a.getText());
 }

}

3.note:

1.因为id=sd1的链接元素在IFrame下的leftframe里面,所以不能直接通过findElement找到该元素,需先切换到IFrame中再切换到leftframe中去

2.如果元素在iframe、frame中需切换到相应的iframe、frame中,但frameset无需切换

3.在切换到leftFrame时,刚开始使用 chrome.switchTo().frame("leftFrame");//leftFrame为frame的name值,但用此方法始终报错:找不到该frame;然后尝试先用xpath通过name找到该frame元素,然后用该frame元素作为参数进行切换,最终切换成功

4.切换iframe或frame时,如果不确定是否切换到目标frame,可以用getPageSource()获取页面信息进行查看

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值