一、环境配置
二、浏览器适配
//1.设置浏览器的位置,google浏览器位置是默认且固定在电脑里的
//2.设置浏览器驱动的位置,C:\Users\27743\AppData\Local\Google\Chrome\Application
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//3.加载浏览器
// ChromeDriver chromeDriver = new ChromeDriver();
WebDriver driver = new ChromeDriver();
//4.通过chromeDriver打开浏览器
// chromeDriver.get("https://www.baidu.com/");
driver.get("https://www.baidu.com/");
这里配置selenium环境,推荐这篇文章全国大学生软件测试大赛Web应用测试(二)Selenium功能测试环境配置_慕测平台的eclipse插件-优快云博客
通过这篇文章来学习
02_浏览器适配_哔哩哔哩_bilibili 根据这个视频操作
设置自动补全功能
三、浏览器基本操作
package selenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Navigation;
import org.openqa.selenium.WebDriver.Options;
import org.openqa.selenium.chrome.ChromeDriver;
public class demo1 {
public static void main(String[] args) {
try {
// TODO Auto-generated method stub
//1.设置浏览器的位置,google浏览器位置是默认且固定在电脑里的
//2.设置浏览器驱动的位置,C:\Users\27743\AppData\Local\Google\Chrome\Application
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//3.加载浏览器
// ChromeDriver chromeDriver = new ChromeDriver();
WebDriver driver = new ChromeDriver();
//4.通过chromeDriver打开浏览器
// chromeDriver.get("https://www.baidu.com/");
driver.get("https://www.baidu.com/");
Thread.sleep(1500);
//浏览器的操作
//1.浏览器最大化
driver.manage().window().maximize();
// Options manage = driver.manage();
// manage.window().maximize();
Thread.sleep(1500);
//2.获取导航类
// Navigation nat = driver.navigate();
// nat.to("https://www.baidu.com/s?wd=%E6%B8%85%E6%BE%88%E7%9A%84%E7%88%B1%E5%8F%AA%E4%B8%BA%E4%B8%AD%E5%9B%BD&sa=fyb_n_homepage&rsv_dl=fyb_n_homepage&from=super&cl=3&tn=baidutop10&fr=top1000&rsv_idx=2&hisfilter=1");
driver.navigate().to("https://www.baidu.com/s?wd=%E6%B8%85%E6%BE%88%E7%9A%84%E7%88%B1%E5%8F%AA%E4%B8%BA%E4%B8%AD%E5%9B%BD&sa=fyb_n_homepage&rsv_dl=fyb_n_homepage&from=super&cl=3&tn=baidutop10&fr=top1000&rsv_idx=2&hisfilter=1");
Thread.sleep(1500);
//2.1浏览器后退
// nat.back();
driver.navigate().back();
Thread.sleep(1500);
//2.2浏览器前进
// nat.forward();
driver.navigate().forward();
Thread.sleep(1500);
//2.3浏览器的刷新
driver.navigate().refresh();
Thread.sleep(1500);
//3.获取当前标题和url
String title = driver.getTitle();
System.out.println("title:"+ title);
System.out.println("url:"+driver.getCurrentUrl());
//3.1重新打开浏览器,我们看当前的标题和url地址
driver.get("https://www.baidu.com/");
driver.navigate().to("https://yiyan.baidu.com/");
System.out.println("title:"+ driver.getTitle());
System.out.println("url:"+driver.getCurrentUrl());
//last:关闭浏览器
driver.quit();
//last:关闭标签
// driver.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
四、元素的基本操作
package selenium;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class demo2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//1.设置浏览器驱动的位置
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//2.加载浏览器
WebDriver driver = new ChromeDriver();
//3.打开浏览器
driver.get("file:///D:/RuanJian/selenium/code/demo1/index.html");
//4.元素的基本操作,先定位后操作
//定位
WebElement input_name = driver.findElement(By.xpath("//*[@id=\"user2\"]"));
System.out.println(input_name.getAttribute("value"));//测试账号
//清空
input_name.clear();
//输入
input_name.sendKeys("李聪聪");
Thread.sleep(1000);
//获取value属性的内容
String value = input_name.getAttribute("value");//李聪聪
System.out.println(value);
//输入密码
driver.findElement(By.xpath("//*[@id=\"password\"]")).sendKeys("123456");
Thread.sleep(1000);
//单选框选择女
driver.findElement(By.xpath("/html/body/table/tbody/tr[4]/td[2]/input[2]")).click();
Thread.sleep(1000);
//复选框选择唱歌
driver.findElement(By.xpath("/html/body/table/tbody/tr[5]/td[2]/input[3]")).click();
Thread.sleep(1000);
//下拉表单选择陕西,这个比较特殊,先获取这个元素,然后加载成select,最后进行操作
WebElement select_table = driver.findElement(By.xpath("/html/body/table/tbody/tr[6]/td[2]/select"));
Select select = new Select(select_table);
//下拉表单,获取其中的值
List<WebElement> options = select.getOptions();
//法一
for (WebElement webElement : options) {
String text = webElement.getText();
System.out.println(text);
}
//法二
for (int i = 0; i < options.size(); i++) {
WebElement webElement = options.get(i);
String text = webElement.getText();
System.out.println("index"+text);
}
//通过顺序选择 0开始
select.selectByIndex(4);//陕西
Thread.sleep(1000);
//通过文字选择
select.selectByVisibleText("北京");
Thread.sleep(1000);
//点击超链接
driver.findElement(By.xpath("/html/body/table/tbody/tr[8]/td[2]/a")).click();//要确定到超链接那里
Thread.sleep(1000);
driver.navigate().back();
Thread.sleep(1000);
//多行文本输入
driver.findElement(By.xpath("/html/body/table/tbody/tr[9]/td[2]/textarea")).sendKeys("666666");
Thread.sleep(1000);
//5.关闭浏览器
driver.quit();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
五、各种定位方式
package selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class demo3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//1.设置浏览器驱动的位置
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//2.加载浏览器
WebDriver driver = new ChromeDriver();
//3.打开浏览器
driver.get("file:///D:/RuanJian/selenium/code/demo1/index.html");
//最大化
driver.manage().window().maximize();
//定位方法
//4.1 id定位
driver.findElement(By.id("user1")).clear();
driver.findElement(By.id("user1")).sendKeys("1234");
//4.2 name定位
driver.findElement(By.name("username")).sendKeys("congcong");
//4.3 class定位
driver.findElement(By.className("C1")).sendKeys("lcc");
Thread.sleep(1500);
//4.4 标签定位
// driver.findElement(By.tagName("a")).click();
//通过超链接里的文本来定位
//driver.findElement(By.linkText("去我的博客")).click();
//4.5 xpath定位
driver.findElement(By.xpath("/html/body/table/tbody/tr[1]/td[2]/input")).sendKeys("xpath");;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
六、xpath语法
//:网页中的任何位置 *:任何元素 XPath(XML Path Language)是一种用于在XML文档中进行选择节点的查询语言,同样也适用于HTML文档。在Web自动化测试中,XPath是一种常用的元素定位方法。以下是一些常用的XPath定位方式: 1. **节点名称**: ```xpath //div ``` 选择所有的`div`元素。 2. **节点属性**: ```xpath //input[@type='text'] ``` 选择所有`type`属性为`text`的`input`元素。 3. **节点文本**: ```xpath //a[contains(text(),'登录')] ``` 选择文本包含“登录”的`a`元素。 4. **节点位置**: ```xpath (//a)[1] ``` 选择第一个`a`元素。 5. **节点索引**: ```xpath //ul/li[3] ``` 选择第三个`li`元素。 6. **节点关系**: ```xpath //div[@class='container']//a ``` 选择`class`属性为`container`的`div`元素下的所有`a`元素。 7. **节点层级**: ```xpath //div/div/a ``` 选择嵌套在两个`div`元素下的`a`元素。 8. **节点ID**: ```xpath //*[@id='login'] ``` 选择ID为`login`的元素。 9. **节点类名**: ```xpath //*[@class='login'] ``` 选择`class`属性包含`login`的元素。 10. **节点属性值**: ```xpath //*[@name='username'] ``` 选择`name`属性为`username`的元素。 11. **节点属性值包含**: ```xpath //*[@class='btn btn-*'] ``` 选择`class`属性值以`btn btn-`开头的元素。 12. **节点属性值匹配**: ```xpath //*[@class='btn' and contains(@class,'primary')] ``` 选择`class`属性为`btn`且包含`primary`的元素。 13. **节点组合条件**: ```xpath //input[@type='text' and @name='username'] ``` 选择`type`为`text`且`name`为`username`的`input`元素。 14. **节点轴定位**: ```xpath //div[preceding-sibling::h1] ``` 选择前面有`h1`元素的`div`元素。 15. **节点轴和文本**: ```xpath //div[.//text()='Login'] ``` 选择包含文本为“Login”的`div`元素。 XPath提供了丰富的表达式来定位页面元素,可以根据实际情况灵活使用。 使用XPath进行复杂的元素选择时,可以结合多种定位方法和逻辑运算符来精确地定位到目标元素。以下是一些技巧和示例: 1. **使用逻辑运算符**: - `and`:同时满足多个条件。 - `or`:满足任一条件。 - `not()`:不满足括号内的条件。 示例: ```xpath //input[@type='text' and @name='username'] ``` 选择`type`为`text`且`name`为`username`的`input`元素。 2. **使用轴定位**: - `parent`:父节点。 - `ancestor`:所有祖先节点。 - `following-sibling`:同级后续节点。 - `preceding-sibling`:同级前置节点。 - `following`:文档中后续的所有节点。 - `preceding`:文档中前置的所有节点。 示例: ```xpath //div[ancestor::form and @class='login'] ``` 选择在表单内部且类名为`login`的`div`元素。 3. **使用函数**: - `contains()`:检查字符串是否包含指定文本。 - `starts-with()`:检查字符串是否以指定文本开头。 - `ends-with()`:检查字符串是否以指定文本结尾。 - `substring()`:提取字符串的一部分。 - `translate()`:替换字符串中的字符。 示例: ```xpath //a[contains(@href, 'example')] ``` 选择`href`属性包含`example`的`a`元素。 4. **使用索引和位置**: - 使用方括号`[]`来指定元素的位置或索引。 示例: ```xpath //ul/li[3] ``` 选择第三个`li`元素。 5. **使用通配符**: - `*`:匹配任何元素节点。 - `@*`:匹配任何属性节点。 示例: ```xpath //*[@class='btn'] ``` 选择所有`class`属性为`btn`的元素。 6. **使用变量**: - 在XPath中可以使用变量来存储复杂的表达式。 示例: ```xpath let $loginLink := //a[contains(text(),'Login')] return $loginLink/@href ``` 定义一个变量`$loginLink`,存储包含文本“Login”的`a`元素,然后返回这个链接的`href`属性。 7. **使用条件表达式**: - 使用方括号`[]`内的表达式作为条件。 示例: ```xpath //div[@class='container' and .//a[text()='Login']] ``` 选择`class`属性为`container`且包含文本为“Login”的`a`元素的`div`。 8. **使用文本匹配**: - 使用`contains()`、`starts-with()`、`ends-with()`等函数进行文本匹配。 示例: ```xpath //button[starts-with(text(),'Submit')] ``` 选择文本以“Submit”开头的`button`元素。 9. **使用相对路径**: - 使用`.`表示当前节点,`..`表示父节点。 示例: ```xpath .//div[@class='content'] ``` 选择当前节点下的`class`属性为`content`的`div`元素。 10. **使用节点轴和文本**: - 结合节点轴和文本函数。 示例: ```xpath //div[.//text()='Login'] ``` 选择包含文本为“Login”的`div`元素。 通过组合使用这些技巧,可以构建出非常精确和复杂的XPath表达式,以满足各种复杂的元素选择需求。 在使用XPath进行元素定位时,确实会遇到一些常见的错误。以下是一些避免错误的技巧: 1. **确保元素存在**: - 在尝试定位元素之前,确保该元素已经加载到页面上。 - 使用显式等待或检查元素是否存在。 2. **使用正确的节点类型**: - 确保使用正确的节点类型(元素节点、属性节点等)。 3. **避免使用绝对路径**: - 绝对路径可能会因为页面结构的微小变化而失效。 - 使用相对路径可以提高定位的灵活性和稳定性。 4. **避免使用ID定位**: - 如果可能,避免使用ID定位,因为ID可能会被页面上的JavaScript动态更改。 5. **使用稳定的属性**: - 选择那些不太可能改变的属性,如`data-*`属性。 6. **避免使用索引**: - 页面上的元素顺序可能会变化,导致基于索引的XPath失效。 - 使用其他更稳定的属性进行定位。 7. **处理动态内容**: - 对于动态生成的内容,尝试使用事件监听或等待元素出现。 8. **避免使用文本节点**: - 文本节点可能会因为空白字符或换行符的存在而难以定位。 - 使用元素的文本内容进行定位时,考虑使用`normalize-space()`函数。 9. **处理特殊字符**: - 在XPath中,特殊字符(如引号、括号等)需要使用`\`进行转义。 10. **使用函数进行文本匹配**: - 使用`contains()`、`starts-with()`、`ends-with()`等函数进行文本匹配,而不是直接匹配文本节点。 11. **避免使用硬编码的值**: - 避免在XPath表达式中硬编码值,如类名、ID等,这些可能会改变。 12. **使用CSS选择器**: - 如果可能,使用CSS选择器代替XPath,因为CSS选择器通常更简洁、更易于理解。 13. **测试XPath表达式**: - 在实际使用XPath表达式之前,使用在线工具或浏览器的开发者工具进行测试。 14. **处理iframe**: - 如果元素位于iframe中,需要先定位到iframe元素,然后使用`frame`或`iframe`定位到目标元素。 15. **避免使用XPath的`//`**: - 使用`//`可能会导致XPath表达式过于宽泛,增加查找时间。 - 尽量限制XPath表达式的搜索范围。 16. **考虑使用属性选择器**: - 属性选择器通常比文本选择器更稳定。 17. **处理多元素选择**: - 如果XPath表达式返回多个元素,确保你的代码能够正确处理这种情况。 18. **使用XPath版本**: - 确保你使用的XPath版本与你的测试工具或库兼容。 19. **避免使用XPath轴**: - 除非必要,否则避免使用XPath轴,因为它们可能会使XPath表达式变得复杂。 20. **持续维护**: - 页面结构可能会变化,定期检查和更新XPath表达式。 通过遵循这些最佳实践,可以减少在使用XPath时遇到的问题,并提高自动化测试的稳定性和可靠性。
package selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class demo4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//1.设置浏览器驱动的位置
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//2.加载浏览器
WebDriver driver = new ChromeDriver();
//3.打开浏览器
driver.get("file:///D:/RuanJian/selenium/code/demo1/index.html");
//最大化
driver.manage().window().maximize();
//xpath定位方式
// //*[@id=\"user1\"] 双杠是任何位置
// 这个是绝对路径:/html/body/table/tbody/tr[8]/td[2]/a 相对路径 : /html/body//a
// //的使用
driver.findElement(By.xpath("//a")).click();
driver.navigate().back();
// //*的使用
driver.findElement(By.xpath("//*[@id='user1']")).sendKeys("666666");
driver.findElement(By.xpath("//*[@id='user1']")).clear();
driver.findElement(By.xpath("//*[@name='username']")).sendKeys("9999999");
// 绝对加相对的方式/ + // /html/body/table/tbody/tr[3]//input 输入密码的tr下面只有一个input
driver.findElement(By.xpath("/html/body/table/tbody/tr[3]//input")).sendKeys("lll");
//多属性找法 //input@[@type=\"text\" and @class=\"C1\"] 查找页面上任何位置的input,但是type是text且classname是C1
driver.findElement(By.xpath("//input[@type=\"text\" and @class=\"C1\"]")).clear();
}
}
七、二次定位和组识别
package selenium;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class demo5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//1.设置浏览器驱动的位置
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//2.加载浏览器
WebDriver driver = new ChromeDriver();
//3.打开浏览器
driver.get("https://www.bjwlxy.cn/");
//
WebElement ul = driver.findElement(By.xpath("/html/body/div[7]/div/div[2]/ul"));
//二次定位
List<WebElement> list = ul.findElements(By.tagName("li"));
for (WebElement webElement : list) {
WebElement a = webElement.findElement(By.tagName("a"));
System.out.println(a.getText());
}
// 如果定位元素有多个 不写序号 代表一类/html/body/div[3]/div/ul/li
List<WebElement> llis = driver.findElements(By.xpath("/html/body/div[3]/div/ul/li"));
for (WebElement webElement : llis) {
WebElement a = webElement.findElement(By.tagName("a"));
System.out.println(a.getText());
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
八、iframe操作
package selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class demo8iframe操作 {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
// 1.设置浏览器驱动的位置
System.setProperty("webdriver.chrome.driver",
"D:\\RuanJian\\google\\chrome-win64\\chrome-win64\\chromedriver.exe");
// 2.加载浏览器
WebDriver driver = new ChromeDriver();
// 3.打开浏览器
driver.get("https://mail.163.com/");
driver.manage().window().maximize();
// xpath的灵活运用,一种是多个属性进行定位,另一个是多个//进行定位
// x-URS-iframe1728614886988.4062
// x-URS-iframe1728615395521.3267
// 不能用id进行定位,因为刷新页面之后,这个id会改变
// 弄一个加载时间,使用显式等待(Explicit Wait)来确保元素在操作前是可交互的,从而减少因页面加载延迟导致的定位问题
WebDriverWait wait = new WebDriverWait(driver, 10);
// 使用显式等待直到元素可见,再找到iframe
WebElement iframe = wait
.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//iframe[@scrolling=\"no\"]")));
// 找到iframe
// WebElement iframe =
// driver.findElement(By.xpath("//iframe[@scrolling=\"no\"]"));
// 切换到iframe
driver.switchTo().frame(iframe);
// 进行操作
// 因为id里包含数字,所以不能用id进行定位
// 用name进行定位
driver.findElement(By.name("email")).sendKeys("1");// 用这个name进行定位的时候就可以,好像不用等待
Thread.sleep(1000);
driver.findElement(By.name("email")).clear();
// 用class进行定位
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".j-inputtext.dlemail.j-nameforslide")));
// 与元素交互
element.sendKeys("2");
Thread.sleep(1000);
element.clear();
// 用xpath进行定位
/// 方式一
driver.findElement(By.xpath(
"//input[@data-placeholder=\"邮箱账号或手机号码\" and @name=\"email\" and @data-type=\"email\" and @data-loginname=\"loginEmail\"]"))
.sendKeys("3");
Thread.sleep(1000);
driver.findElement(By.xpath(
"//input[@data-placeholder=\"邮箱账号或手机号码\" and @name=\"email\" and @data-type=\"email\" and @data-loginname=\"loginEmail\"]"))
.clear();
// 方式二 //*[@id="account-box"]//input (手写xpath的方式)
driver.findElement(By.xpath("//*[@id=\"account-box\"]//input")).sendKeys("888888");
// WebElement iframe = wait.until(new ExpectedCondition<WebElement>() {
//
// @Override
// public WebElement apply(WebDriver arg0) {
// // TODO Auto-generated method stub
// return driver.findElement(By.xpath("//iframe[@scrolling=\"no\"]"));
// }
// });
// Thread.sleep(1000);
}
}
九、延迟调用
package selenium;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class demo9延迟调用 {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//设置浏览器的位置
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//加载浏览器
// ChromeDriver chromeDriver = new ChromeDriver();
WebDriver driver = new ChromeDriver();
//通过chromeDriver打开浏览器
driver.get("https://www.baidu.com/");
Thread.sleep(1500);
driver.manage().window().maximize();
//上传文件
driver.findElement(By.className("soutu-btn")).click();
WebElement fileInput = driver.findElement(By.className("upload-pic"));
//D:\\image\\deskbook\\mimi.jpg
File file = new File("D:\\image\\deskbook\\mimi.jpg");
if(file.exists()) {
fileInput.sendKeys(file.getPath());
}
}
}
十、xpath案例
package selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class demo8 {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//1.设置浏览器驱动的位置
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//2.加载浏览器
WebDriver driver = new ChromeDriver();
//3.打开浏览器
driver.get("https://mail.163.com/");
driver.manage().window().maximize();
//xpath的灵活运用,一种是多个属性进行定位,另一个是多个//进行定位
//x-URS-iframe1728614886988.4062
//x-URS-iframe1728615395521.3267
//不能用id进行定位,因为刷新页面之后,这个id会改变
//弄一个加载时间,使用显式等待(Explicit Wait)来确保元素在操作前是可交互的,从而减少因页面加载延迟导致的定位问题
WebDriverWait wait = new WebDriverWait(driver, 10);
// 使用显式等待直到元素可见,再找到iframe
WebElement iframe = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//iframe[@scrolling=\"no\"]")));
//找到iframe
//WebElement iframe = driver.findElement(By.xpath("//iframe[@scrolling=\"no\"]"));
//切换到iframe
driver.switchTo().frame(iframe);
//进行操作
//因为id里包含数字,所以不能用id进行定位
//用name进行定位
driver.findElement(By.name("email")).sendKeys("1");//用这个name进行定位的时候就可以,好像不用等待
Thread.sleep(1000);
driver.findElement(By.name("email")).clear();
//用class进行定位
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".j-inputtext.dlemail.j-nameforslide")));
//与元素交互
element.sendKeys("2");
Thread.sleep(1000);
element.clear();
//用xpath进行定位
///方式一
driver.findElement(By.xpath("//input[@data-placeholder=\"邮箱账号或手机号码\" and @name=\"email\" and @data-type=\"email\" and @data-loginname=\"loginEmail\"]")).sendKeys("3");
Thread.sleep(1000);
driver.findElement(By.xpath("//input[@data-placeholder=\"邮箱账号或手机号码\" and @name=\"email\" and @data-type=\"email\" and @data-loginname=\"loginEmail\"]")).clear();
//方式二 //*[@id="account-box"]//input (手写xpath的方式)
driver.findElement(By.xpath("//*[@id=\"account-box\"]//input")).sendKeys("888888");
// WebElement iframe = wait.until(new ExpectedCondition<WebElement>() {
//
// @Override
// public WebElement apply(WebDriver arg0) {
// // TODO Auto-generated method stub
// return driver.findElement(By.xpath("//iframe[@scrolling=\"no\"]"));
// }
// });
//Thread.sleep(1000);
}
}
十一、上传文案
元素定位是自动化测试中的一个核心概念,特别是在使用Selenium、Appium等自动化测试工具时。定位元素是告诉测试工具“在哪里”找到页面上的特定元素。以下是一些常用的元素定位方法: ### 1. ID - **描述**: 每个元素的唯一标识符。 - **示例**: `<input id="username">` - **定位方法**: `driver.find_element_by_id("username")` ### 2. Name - **描述**: 元素的名称属性。 - **示例**: `<input name="password">` - **定位方法**: `driver.find_element_by_name("password")` ### 3. Class Name - **描述**: 元素的class属性,可能不唯一。 - **示例**: `<div class="button">` - **定位方法**: `driver.find_element_by_class_name("button")` ### 4. Tag Name - **描述**: 元素的标签名。 - **示例**: `<button>` - **定位方法**: `driver.find_element_by_tag_name("button")` ### 5. CSS Selector - **描述**: 使用CSS选择器定位元素。 - **示例**: `div.button` - **定位方法**: `driver.find_element_by_css_selector("div.button")` ### 6. XPath - **描述**: 使用XPath表达式定位元素。 - **示例**: `//div[@class='button']` - **定位方法**: `driver.find_element_by_xpath("//div[@class='button']")` ### 7. Link Text - **描述**: 定位具有特定文本的链接。 - **示例**: `<a href="#">Click Here</a>` - **定位方法**: `driver.find_element_by_link_text("Click Here")` ### 8. Partial Link Text - **描述**: 定位包含特定文本的链接。 - **示例**: `<a href="#">Click</a>` - **定位方法**: `driver.find_element_by_partial_link_text("Click")` ### 9. Selector - **描述**: 使用Selenium的WebDriverWait和expected_conditions来定位元素,支持多种定位策略。 - **示例**: ```python from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.button"))).click() ``` ### 注意事项 - 在实际应用中,选择哪种定位方法取决于页面元素的特性和测试需求。 - 优先使用ID和Name定位,因为它们通常更稳定和快速。 - CSS和XPath提供了非常强大的定位能力,但可能会因为页面结构的改变而变得脆弱。 - 在编写自动化测试脚本时,建议使用显式等待来确保元素在进行操作前是可见和可交互的。 根据你的具体需求和测试环境,选择最适合的定位策略。如果你需要更具体的帮助,比如如何在特定情况下使用这些定位方法,或者如何解决定位问题,请提供更多的上下文信息。
显式等待(Explicit Wait)是自动化测试中的一种等待机制,用于等待某个条件成立后再继续执行测试脚本。与隐式等待(Implicit Wait)不同,显式等待提供了更灵活的等待条件,允许你等待某个特定的条件,直到该条件满足为止。显式等待通常用于处理页面加载时间的不确定性,确保在进行下一步操作之前页面上的元素是可见的、可点击的、可选中的等。 在Selenium中,显式等待通常使用`WebDriverWait`类结合`expected_conditions`模块来实现。以下是一些常见的使用场景和示例: ### 常见的等待条件(Expected Conditions): - `element_to_be_clickable(locator)`: 等待元素可点击。 - `presence_of_element_located(locator)`: 等待元素存在于DOM中。 - `visibility_of_element_located(locator)`: 等待元素可见。 - `visibility_of_all_elements_located(locator)`: 等待所有元素可见。 - `text_to_be_present_in_element(locator, text)`: 等待元素中包含特定文本。 - `frame_to_be_available_and_switch_to_it(locator)`: 等待frame可用并切换到该frame。 ### 示例代码: ```python from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 启动浏览器驱动 driver = webdriver.Chrome() # 打开网页 driver.get("http://example.com") # 使用显式等待等待某个元素可点击 try: # 设置最长等待时间为10秒 element = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "myButton")) # 等待ID为"myButton"的元素可点击 ) # 点击元素 element.click() finally: # 关闭浏览器 driver.quit() ``` ### 注意事项: - 显式等待比隐式等待更灵活,因为它允许你等待特定的条件,而不是简单地等待一个固定的时间。 - 显式等待可以减少测试脚本的执行时间,因为它只在需要时等待。 - 使用显式等待时,需要导入`WebDriverWait`和`expected_conditions`模块。 - 显式等待可以与多种定位策略(如ID、CSS选择器、XPath等)结合使用。 显式等待是自动化测试中非常重要的一个概念,它能显著提高测试的稳定性和效率。
package selenium;
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class demo9 {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//设置浏览器的位置
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//加载浏览器
// ChromeDriver chromeDriver = new ChromeDriver();
WebDriver driver = new ChromeDriver();
//通过chromeDriver打开浏览器
driver.get("https://www.baidu.com/");
Thread.sleep(1500);
driver.manage().window().maximize();
//上传文件
driver.findElement(By.className("soutu-btn")).click();
WebElement fileInput = driver.findElement(By.className("upload-pic"));
//D:\\image\\deskbook\\mimi.jpg
File file = new File("D:\\image\\deskbook\\mimi.jpg");
if(file.exists()) {
fileInput.sendKeys(file.getPath());
}
}
}
十二、截屏处理
package selenium;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class demo10 {
public static void main(String[] args) throws InterruptedException, IOException {
// TODO Auto-generated method stub
//设置浏览器的位置
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//加载浏览器
// ChromeDriver chromeDriver = new ChromeDriver();
WebDriver driver = new ChromeDriver();
//通过chromeDriver打开浏览器
driver.get("https://www.baidu.com/");
Thread.sleep(1500);
driver.manage().window().maximize();
// WebDriverWait wait = new WebDriverWait(driver, 10);
// wait.until(ExpectedConditions.titleIs("百度一下,你就知道"));
TakesScreenshot screenshot = (TakesScreenshot) driver;
File file = screenshot.getScreenshotAs(OutputType.FILE);
String title = driver.getTitle();
FileUtils.copyFile(file, new File("D:\\image\\deskbook\\"+ title +".png"));
//*[@id="hotsearch-content-wrapper"]/li[3]/a/span[2]
// WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\"hotsearch-content-wrapper\"]/li[3]/a/span[2]")));
// element.click();
// wait.until(ExpectedConditions.titleIs("中方谴责以军袭击联合国驻黎部队"));
driver.get("https://image.baidu.com/");//截不到百度地图
Thread.sleep(3000);
File file1 = screenshot.getScreenshotAs(OutputType.FILE);
String title1 = driver.getTitle();
FileUtils.copyFile(file, new File("D:\\image\\deskbook\\"+ title1 +".png"));
}
}
十三、键盘模拟焦点切换
package selenium;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class demo11 {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//设置浏览器的位置
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//加载浏览器
// ChromeDriver chromeDriver = new ChromeDriver();
WebDriver driver = new ChromeDriver();
//通过chromeDriver打开浏览器
driver.get("https://www.yinxiang.com/");
//driver.get("https://www.baidu.com/");
//键盘模拟焦点切换
// //
// TakesScreenshot screenshot = (TakesScreenshot) driver;//driver是实现了TakesScreenshot接口(获取屏幕截屏)
// File file = screenshot.getScreenshotAs(OutputType.FILE);//调用getScreenshotAs方法,并以截图以文件的形式返回
// String title = driver.getTitle();//获取浏览器的标题
// //D:\image\test
// FileUtils.copyFile(file, new File("D:\\image\\test\\"+ title +".png"));//将截图文件保存在指定的文件夹
//支持所有的按键
Keys[] allKeys = Keys.values();
for (Keys keys : allKeys) {
System.out.println(keys.name());
System.out.println(keys.getCodePoint());
System.out.println("______________");
}
// //*[@id="mega-menu-item-23530"]/a //*[@id="mega-menu-item-23530"]/a 这里为啥就不行了
// WebDriverWait wait = new WebDriverWait(driver, 20);
// WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".mega-menu-link")));
// element.click();
//点击操作
//driver.findElement(By.className("mega-menu-link")).click();这个不行
driver.findElement(By.xpath("//*[@id=\"mega-menu-item-23530\"]/a")).click();
//输值操作
driver.findElement(By.xpath("//*[@id=\"root\"]/div/div/div/div[2]/div/div[2]/div[1]/div[1]/div/input")).sendKeys("27743", Keys.TAB, "666666");
driver.findElement(By.className("registration-account-input")).sendKeys("9999",Keys.TAB, "0000");
}
}
十四、悬停操作
package selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class demo12悬停操作 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//设置浏览器的位置
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//加载浏览器
// ChromeDriver chromeDriver = new ChromeDriver();
WebDriver driver = new ChromeDriver();
driver.get("https://www.jd.com/?cu=true&utm_source=baidu-pinzhuan&utm_medium=cpc&utm_campaign=t_288551095_baidupinzhuan&utm_term=0f3d30c8dba7459bb52f2eb5eba8ac7d_0_0b4589f0470d409b83b8bcd894e9dc5c");
//鼠标悬停实现分栏
Actions actions = new Actions(driver);
//鼠标的操作 左右单击 悬停 拖拽
// //鼠标移动
// actions.moveByOffset(100, 100).perform();;
// //右单击
// actions.contextClick().perform();
//先找到phone
WebElement phone = driver.findElement(By.xpath("//*[@id=\"J_cate\"]/ul/li[2]/a[1]"));
//通过x,y定位
//actions.moveByOffset(phone.getLocation().x, phone.getLocation().y).perform();
//
// actions.moveToElement(phone);
// actions.clickAndHold().perform();
//
actions.clickAndHold(phone).perform();
}
}
十五、滚动加载
package selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class demo13滚动加载 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//初始化WebDriver
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//加载浏览器
// ChromeDriver chromeDriver = new ChromeDriver();
WebDriver driver = new ChromeDriver();
//打开网页
driver.get("https://www.jd.com/?cu=true&utm_source=baidu-pinzhuan&utm_medium=cpc&utm_campaign=t_288551095_baidupinzhuan&utm_term=0f3d30c8dba7459bb52f2eb5eba8ac7d_0_0b4589f0470d409b83b8bcd894e9dc5c");
//滚动加载,scrollTo(x, y) 方法用于滚动页面到指定的坐标位置,页面向下滚动了1000像素
JavascriptExecutor executor = (JavascriptExecutor) driver;
//executor.executeScript("window.scrollTo(0,1000)");
//滑动到指定元素的位置,企业计划购
WebElement QiYeJiHuaGou = driver.findElement(By.xpath("//*[@id=\"J_service\"]/div[1]/ul/li[10]/a/i"));
//executor.executeScript("window.scrollTo(0," +QiYeJiHuaGou.getLocation().y+ ")");
//滑动方式二 arguments[0].scrollIntoView() rguments 是一个类数组对象,它存在于函数内部,用于存储传递给函数的所有参数。arguments[0] 表示第一个参数
executor.executeScript("arguments[0].scrollIntoView()", QiYeJiHuaGou);
// 等待元素可见并点击
WebDriverWait wait = new WebDriverWait(driver, 20);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"JD_activity-main\"]/div/div/div/div/div/a[11]/div[2]/div/img")));
element.click();
}
}
十六、日期设置
package selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import com.gargoylesoftware.htmlunit.javascript.background.JavaScriptExecutor;
public class demo14日期设置 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//初始化WebDriver
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//加载浏览器
// ChromeDriver chromeDriver = new ChromeDriver();
WebDriver driver = new ChromeDriver();
//打开网页
driver.get("https://www.12306.cn/index/");
//driver.get("http://localhost:7000/#/emp");
//日期设置
WebElement date = driver.findElement(By.id("train_date"));
//假如我们直接输入数字输入不进去,我们
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].removeAttribute('randonly')", date);
date.clear();
date.sendKeys("hab");
}
}
十七、切换标签
package selenium;
import java.util.ArrayList;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class demo15切换标签 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//初始化WebDriver
System.setProperty("webdriver.chrome.driver", "C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
//加载浏览器
// ChromeDriver chromeDriver = new ChromeDriver();
WebDriver driver = new ChromeDriver();
//打开网页
driver.get("https://baoji.58.com/?utm_source=market&spm=u-2d2yxv86y3v43nkddh1.BDPCPZ_BT");
//切换标签
System.out.println(driver.getTitle());//【58同城 58.com】宝鸡分类信息 - 本地 免费 高效
driver.findElement(By.xpath("//*[@id=\"escNav\"]/em/a[2]")).click();
System.out.println(driver.getTitle());//【58同城 58.com】宝鸡分类信息 - 本地 免费 高效
driver.findElement(By.xpath("//*[@id=\"commonTopbar_vip\"]/a")).click();
System.out.println(driver.getTitle());//【58同城 58.com】宝鸡分类信息 - 本地 免费 高效,说明没有切换标签页
//每一项代表一个窗口
Set<String> window = driver.getWindowHandles();
ArrayList<String> window_list = new ArrayList<>(window);
// for (String string : window) {
// System.out.println(string);
// }
driver.switchTo().window(window_list.get(window_list.size()-1));
System.out.println(driver.getTitle());//第一个跳转的页面
driver.switchTo().window(window_list.get(window_list.size()-2));
System.out.println(driver.getTitle());//第二个跳转的页面
}
}
十八、自动登录
十九、模块适配
package selenium;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class demo17模块切换 {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 初始化WebDriver
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\27743\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
// 加载浏览器
// ChromeDriver chromeDriver = new ChromeDriver();
WebDriver driver = new ChromeDriver();
// 打开网页
driver.get("https://www.zentao.net/");
// 最大化
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("header")));
WebElement nav = element.findElement(By.id("navbar"));
System.out.println("a");
List<WebElement> li = nav.findElements(By.tagName("li"));
System.out.println("找到 " + li.size() + " 个列表项");
// 悬停
Actions actions = new Actions(driver);
actions.moveToElement(driver.findElement(By.xpath("//*[@id=\"navbarCollapse\"]/ul/li[2]/a")));
actions.pause(2000);
actions.perform();
WebElement nav1 = driver.findElement(By.className("row")); // 假设导航栏的类名为 "nav"
// System.out.println("b");
WebElement specificUl = nav1.findElement(By.xpath("//*[@id=\"navbarCollapse\"]/ul")); // 假设ul的类名为
// System.out.println("b");
// *[@id="navbarCollapse"]/ul
List<WebElement> lis = specificUl.findElements(By.xpath("./li"));
// System.out.println(lis.size());// 获取所有 li 子元素
lis.get(1).findElement(By.tagName("a")).click(); // 点击 a 标签
// driver.quit();
}
}
二十、数据参数读取
package jxl;
import java.io.File;
import java.io.IOException;
import jxl.read.biff.BiffException;
public class deno1 {
public static void main(String[] args) throws BiffException, IOException {
// TODO Auto-generated method stub
File file = new File("D:\\RuanJian\\selenium\\code\\文件.xls");
Workbook workbook = Workbook.getWorkbook(file);
Sheet sheet_1 = workbook.getSheet(0);
Cell cell1 = sheet_1.getCell(0, 1);
System.out.println(cell1.getContents());
System.out.println(sheet_1.getRows());
System.out.println(sheet_1.getColumns());
for (int i = 0; i < sheet_1.getColumns(); i++) {
Cell cell2 = sheet_1.getCell(i, 0);
System.out.println(cell2.getContents());
}
for (int i = 0; i < sheet_1.getRows(); i++) {
for (int j = 0; j < sheet_1.getColumns(); j++) {
Cell cell3 = sheet_1.getCell(j, i);
System.out.print(cell3.getContents() +" ");
}
System.out.println();
}
}
}