作用: 自动化Web应用程序以进行测试
官方网址: https://www.selenium.dev/zh-cn/
文档地址: https://www.selenium.dev/zh-cn/documentation/webdriver/
Java依赖下载
<dependency>
<groupId>org.seleniumhq.seleniumgroupId>
<artifactId>selenium-javaartifactId>
<version>4.1.2version>
dependency>
驱动下载 == 必须跟浏览器的版本对应上,否则会报错哦
地址: https://www.selenium.dev/zh-cn/documentation/webdriver/getting_started/install_drivers/
当然驱动不想自己手动下载的话,让第三方驱动管理来帮你下自动适配你的浏览器所对应上的驱动。然后手动导入到IDEA上: https://github.com/bonigarcia/webdrivermanager**
package work.linruchang.qq;
import io.github.bonigarcia.wdm.WebDriverManager;
import lombok.SneakyThrows;
import org.junit.Test;
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.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
/**
* 作用:
*
* @author LinRuChang
* @version 1.0
* @date 2022/02/07
* @since 1.8
**/
public class SeleniumTest {
/**
* 谷歌测试
* 指定某个浏览器的作用:感觉仅仅只是用于谷歌浏览器的绿色版本,因为第三方的谷歌浏览器基本就不生效
* 缺陷:使用如百分浏览器、奶牛浏览器、星愿浏览器等第三方魔改谷歌浏览器基本都不生效,在selenium没找到这几个浏览器的Chromium驱动版本号
* 第三方驱动包自动适配驱动版本无需手动指定WebDriverManager:https://github.com/bonigarcia/webdrivermanager
*/
@Test
@SneakyThrows
public void chromeTest() {
//设置驱动
//System.setProperty("webdriver.chrome.driver", "G:\\Selenium\\driver\\chrome\\98.0.4758.80\\chromedriver.exe");
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("https://read.douban.com/reader/column/4639817/chapter/24562734/?dcs=column&dcm=chapter-list");
//获取文章标题
WebElement titleContentElement = driver.findElement(By.xpath("//div[@class='chapter-header']/h1"));
String titleContent = titleContentElement.getText();
System.out.println(titleContent);
//获取文章内容(此div包含标题)
WebElement articleContentElement = driver.findElement(By.xpath("//div[@class='article']"));
String articleContent = articleContentElement.getText();
System.out.println(articleContent);
//关闭浏览器
driver.close();
}
/**
* Edge测试
*
* 第三方驱动包自动适配驱动版本无需手动指定WebDriverManager:https://github.com/bonigarcia/webdrivermanager
*/
@Test
@SneakyThrows
public void edgeTest() {
//设置驱动
//System.setProperty("webdriver.edge.driver", "G:\\Selenium\\driver\\edge\\98.0.1108.43\\edgedriver_win64\\msedgedriver.exe");
WebDriverManager.edgedriver().setup();
WebDriver driver = new EdgeDriver();
driver.get("https://read.douban.com/reader/column/4639817/chapter/24562734/?dcs=column&dcm=chapter-list");
//获取文章标题
WebElement titleContentElement = driver.findElement(By.xpath("//div[@class='chapter-header']/h1"));
String titleContent = titleContentElement.getText();
System.out.println(titleContent);
//获取文章内容(此div包含标题)
WebElement articleContentElement = driver.findElement(By.xpath("//div[@class='article']"));
String articleContent = articleContentElement.getText();
System.out.println(articleContent);
//关闭浏览器
driver.close();
}
/**
* 火狐测试
*
* 第三方驱动包自动适配驱动版本无需手动指定WebDriverManager:https://github.com/bonigarcia/webdrivermanager
*/
@Test
@SneakyThrows
public void firefoxTest() {
//参考 {@link org.openqa.selenium.firefox.FirefoxDriver.SystemProperty}
//浏览器可执行程序 == 不指定则默认使用C:\Program Files\Mozilla Firefox\firefox.exe
//System.setProperty("webdriver.firefox.bin", "C:\\Program Files\\Firefox Developer Edition\\firefox.exe");
//浏览器驱动包
//System.setProperty("webdriver.gecko.driver", "G:\\Selenium\\driver\\firefox\\89\\geckodriver.exe");
WebDriverManager.firefoxdriver().setup();
WebDriver driver = new FirefoxDriver();
driver.get("https://read.douban.com/reader/column/4639817/chapter/24562734/?dcs=column&dcm=chapter-list");
//获取文章标题
WebElement titleContentElement = driver.findElement(By.xpath("//div[@class='chapter-header']/h1"));
String titleContent = titleContentElement.getText();
System.out.println(titleContent);
//获取文章内容(此div包含标题)
WebElement articleContentElement = driver.findElement(By.xpath("//div[@class='article']"));
String articleContent = articleContentElement.getText();
System.out.println(articleContent);
//关闭浏览器
driver.close();
}
}
package work.linruchang.qq;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Console;
import cn.hutool.http.HttpUtil;
import lombok.SneakyThrows;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.logging.ConsoleHandler;
/**
* 作用:
*
* @author LinRuChang
* @version 1.0
* @date 2022/02/07
* @since 1.8
**/
public class CrawlerTest {
@Test
@SneakyThrows
public void dousanduTest() {
//设置驱动
System.setProperty("webdriver.chrome.driver", "G:\\Selenium\\driver\\chrome\\98.0.4758.80\\chromedriver.exe");
//WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("https://read.douban.com/column/4639817/chapters?dcs=column&dcm=chapter-list");
//获取目录所有的文章url地址,开始爬
List<WebElement> chapterItemElements = driver.findElements(By.xpath("//a[@class='chapter-item ']"));
chapterItemElements.forEach(chapterItemElement -> {
String href = chapterItemElement.getAttribute("href");
WebElement titleElement = chapterItemElement.findElement(By.xpath("h3"));
String title = titleElement.getText();
Console.log("打开【{}】:{}",title,href);
pageCrawl(href,new File("C:\\Users\\Administrator\\Desktop\\爬虫\\刘宇宁 - 堕三都.txt"));
});
//关闭浏览器
driver.close();
}
/**
* 爬取文章
*/
@SneakyThrows
public static void pageCrawl(String url, File file) {
Assert.notBlank(url);
Assert.notNull(file);
//设置驱动
System.setProperty("webdriver.chrome.driver", "G:\\Selenium\\driver\\chrome\\98.0.4758.80\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get(url);
//获取文章标题
WebElement titleContentElement = driver.findElement(By.xpath("//div[@class='chapter-header']/h1"));
String titleContent = titleContentElement.getText();
System.out.println(titleContent);
//获取文章内容(此div包含标题)
WebElement articleContentElement = driver.findElement(By.xpath("//div[@class='article']"));
String articleContent = articleContentElement.getText();
System.out.println(articleContent);
//文章爬到文件里
Files.write(file.toPath(),articleContent.getBytes(), StandardOpenOption.WRITE,StandardOpenOption.APPEND,StandardOpenOption.CREATE);
Files.write(file.toPath(),"\r\n\r\n\r\n\r\n".getBytes(), StandardOpenOption.WRITE,StandardOpenOption.APPEND,StandardOpenOption.CREATE);
//关闭浏览器
driver.close();
}
}
@Data
@AllArgsConstructor
static class TempContent<T> {
T content;
public static <M> TempContent<M> instance(M content) {
return new TempContent<>(content);
}
}
@Test
@SneakyThrows
public void test1() {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("https://fanyi.youdao.com/");
TempContent<String> tempRowContent = TempContent.instance("");
TempContent<String> tempResultContent = TempContent.instance("");
Stream.of(null,"猫", "狗", "狗", "老师,节日快乐", "码农并不幸福", "I Love You")
.filter(StrUtil::isNotBlank)
.forEachOrdered(rowContent -> {
WebElement inputOriginal = driver.findElement(By.id("inputOriginal"));
inputOriginal.clear();
inputOriginal.sendKeys(rowContent);
//静态等待,直到查到翻译结果打印出来 == 最多等10s,否则抛出异常
WebDriverWait webDriverWait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement transTarget1 = webDriverWait.until(currentDriver -> {
WebElement transTargetElem = driver.findElement(By.id("transTarget"));
String content = transTargetElem.getText();
boolean flag1 = StrUtil.equals(rowContent, tempRowContent.getContent());
boolean flag2 = StrUtil.isNotBlank(content) && !StrUtil.equals(content, tempResultContent.getContent());
return flag1 || flag2 ? transTargetElem : null;
});
String text = transTarget1.getText();
Console.log("【{}】翻译:【{}】", rowContent, text);
tempRowContent.setContent(rowContent);
tempResultContent.setContent(text);
});
//关闭浏览器
driver.quit();
}
package work.linruchang.qq;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import io.github.bonigarcia.wdm.WebDriverManager;
import lombok.SneakyThrows;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
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;
import java.time.Duration;
import java.util.List;
import java.util.stream.Stream;
/**
* 作用:
*
* @author LinRuChang
* @version 1.0
* @date 2022/02/07
* @since 1.8
**/
public class BilibiliTest {
/**
* 通过某位用户的视频展示页面爬取此用户所有视频链接
*/
@Test
@SneakyThrows
public void test1() {
Stream.of("https://space.bilibili.com/615412417/video?tid=0&page=1&keyword=&order=pubdate", "https://space.bilibili.com/501882526/video")
.filter(StrUtil::isNotBlank)
.parallel() //多线程
.forEach(BilibiliTest::linkCapture);
}
/**
* 通过用户名进行爬取每个用户的所有投稿视频播放链接
*/
@Test
@SneakyThrows
public void test2() {
Stream.of("黑马程序员", "尚学堂")
.filter(StrUtil::isNotBlank)
.parallel() //多线程
.forEach(BilibiliTest::likeCaptureByUserName);
}
/**
* 爬取某用户所有的视频链接
*
* @param userName B站用户名,【仅取用户搜索结果第一个】
*/
@SneakyThrows
public static void likeCaptureByUserName(String userName) {
Assert.notBlank(userName);
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
//等待组件
WebDriverWait webDriverWait = new WebDriverWait(driver, Duration.ofSeconds(20));
driver.manage().window().maximize();
driver.get("https://www.bilibili.com/");
Console.log("当前窗口:{}",driver.getWindowHandle());
//搜索
WebElement searchInput = webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".nav-search-input")));
searchInput.sendKeys(userName + Keys.ENTER);
//这里有坑必须切换新的Tab页去,找了半天才知道为什么后面一直执行不了,超链接点击后如果是新开Tab页面建议直接使用driver.navigate().to让其一直在当前Tab不用去切换
driver.switchTo().window(CollUtil.getLast(driver.getWindowHandles()));
Console.log("当前窗口:{}",driver.getWindowHandle());
WebElement userBtn = webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".v-switcher-header-tabs li:nth-last-of-type(2) a")));
driver.navigate().to(userBtn.getAttribute("href"));
List<WebElement> userInfos = webDriverWait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("#user-list .user-item .headline a:nth-child(1)")));
String userVidowsLink = null;
if (CollUtil.isNotEmpty(userInfos)) {
//查到的首位B站用户
WebElement targetElem = userInfos.get(0);
String targetElemText = targetElem.getText();
driver.navigate().to(targetElem.getAttribute("href"));
//【投稿】元素
WebElement userVidowsLinkElem = webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#navigator a:nth-child(3)")));
userVidowsLink = userVidowsLinkElem.getAttribute("href");
Console.log("输入参数用户名【{}】、结果参数用户名以及对应视频链接地址:【{}】:【{}】", userName, targetElemText, userVidowsLink);
}
//关闭浏览器
driver.quit();
//开始抓取此用户的所有视频链接
linkCapture(userVidowsLink);
}
public static void linkCapture(String url) {
Assert.notBlank(url);
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
//等待组件
WebDriverWait webDriverWait = new WebDriverWait(driver, Duration.ofSeconds(5));
driver.get(url);
//视频所属的用户名
WebElement userNameElem = webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#h-name")));
String userName = userNameElem.getText();
String targetFile = "C:\\Users\\Administrator\\Desktop\\爬虫\\" + userName + ".txt";
Console.log("\n================B站视频归属链接【{}】===================\n", userName);
int page = 0;
int linkCount = 0;
while (true) {
try {
Console.log("\n================第{}页的视频链接===================", ++page);
List<WebElement> elements = webDriverWait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("#submit-video-list .cube-list a[class~=title]")));
linkCount = CollUtil.size(elements) + linkCount;
elements.forEach(element -> {
String content = StrUtil.format("{}:{}", element.getAttribute("title"), element.getAttribute("href"));
Console.log(content);
FileUtil.appendString(StrUtil.addSuffixIfNot(content, "\r\n"), targetFile, "utf-8");
});
//下一页
WebElement nextPage = webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".be-pager-next")));
nextPage.click();
} catch (Exception e) { //等待超时,说明无视频链接了
String content = StrUtil.format("================链接爬取结束,共{}页,总数{}===================", page, linkCount);
Console.log(content);
FileUtil.appendString(StrUtil.addSuffixIfNot(content, "\r\n"), targetFile, "utf-8");
break;
}
}
//关闭浏览器
driver.quit();
}
}
本地静态页面 == C:/Users/Administrator/Desktop/index.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
head>
<body>
<a id="testA" href="javascript:;">See an example alerta>
<button id="alertBtn">See an example alertbutton>
body>
<script src="G:\VsCode\开源\jquery-3.5.1\jquery-3.5.1.min.js">script>
<script>
$(function(){
$("#alertBtn").click(() => {
console.log("点击alertBtn")
});
$("#testA").click(() => {
//确定按钮
// alert("点击a标签")
//确定、取消按钮
// confirm("水电费第三方第三方confirm")
//可输入内容、确定、取消按钮
var content = prompt("神鼎飞丹砂发顺丰prompt弹框")
alert(`prompt手动输入的内容:${content}`)
})
})
script>
html>
java
package work.linruchang.qq;
import cn.hutool.core.lang.Console;
import io.github.bonigarcia.wdm.WebDriverManager;
import lombok.SneakyThrows;
import org.junit.Test;
import org.openqa.selenium.Alert;
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.edge.EdgeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
/**
* 作用:
*
* @author LinRuChang
* @version 1.0
* @date 2022/02/07
* @since 1.8
**/
public class BrowserTest {
@Test
@SneakyThrows
public void test1() {
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("file:///C:/Users/Administrator/Desktop/index.html");
//获取含有内容【See an example alert】的a标签节点
WebElement webElement = driver.findElement(By.linkText("See an example alert"));
webElement.click();
//最多等待5秒弹框出现,如果依然没有则抛出异常
Alert alert = new WebDriverWait(driver, Duration.ofSeconds(5)).until(ExpectedConditions.alertIsPresent());
//Store the alert text in a variable
String text = alert.getText();
Console.log("弹框信息:{}",text);
//填充prompt输入框内容
alert.sendKeys("你好我是手动输入的内容");
//关闭弹框 = 确认按钮 == alert、confirm、prompt
alert.accept();
//关闭弹框 = 取消按钮 = prompt
//alert.dismiss();
//仅prompt可输入内容
if(text.contains("prompt弹框")) {
Alert promptEndResult = new WebDriverWait(driver, Duration.ofSeconds(5)).until(ExpectedConditions.alertIsPresent());
String promptEndResultContent = promptEndResult.getText();
Console.log("弹框结束后的信息:{}",promptEndResultContent);
}
//关闭浏览器
//driver.quit();
}
}
@Test
@SneakyThrows
public void test2() {
WebDriverManager.firefoxdriver().setup();
FirefoxDriver driver = new FirefoxDriver();
driver.get("https://www.baidu.com/");
//百度输入框
WebElement kw = driver.findElement(By.id("kw"));
kw.sendKeys("selenium入门学习");
//搜索框的结果:selenium入门学习ABCtre
Actions actions = new Actions(driver);
actions.keyDown(Keys.SHIFT).sendKeys(kw, "abc")
.keyUp(Keys.SHIFT).sendKeys(kw, "tre")
.perform();
//【百度一下】 按钮
WebElement su = driver.findElement(By.id("su"));
su.click();
//这句等价于上面的两句 == 回车即查询
//kw.sendKeys(Keys.ENTER);
//将查询结果打印出来
WebElement searchResultContentElement = driver.findElement(By.id("content_left"));
String searchResultContent = searchResultContentElement.getText();
Console.log(searchResultContent);
//关闭浏览器
driver.quit();
}
//等待5秒后在执行后续代码
Thread.sleep(5000);
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
head>
<body>
<a id="testA" href="javascript:;">See an example alerta>
<button id="alertBtn">See an example alertbutton>
body>
<script src="G:\VsCode\开源\jquery-3.5.1\jquery-3.5.1.min.js">script>
<script>
$(function(){
$("#alertBtn").click(() => {
console.log("点击alertBtn")
});
$("#testA").click(() => {
//确定按钮
// alert("点击a标签")
//确定、取消按钮
// confirm("水电费第三方第三方confirm")
//可输入内容、确定、取消按钮
var content = prompt("神鼎飞丹砂发顺丰prompt弹框")
alert(`prompt手动输入的内容:${content}`)
})
setTimeout(() => {
$("body").append("延迟3秒后插入的节点内容
");
},3000)
setTimeout(() => {
$("body").append("延迟4秒后插入的节点内容
");
},4000)
})
script>
html>
/**
* 隐式等待
*/
@Test
@SneakyThrows
public void test5() {
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("C:\\Users\\Administrator\\Desktop\\index.html");
//针对全局有效,整个生命周期,在设置的超时时间范围内不断查找元素,直到5秒仍然找不到则报错
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
WebElement delayElementId = driver.findElement(By.id("delayElementId"));
String text = delayElementId.getText();
Console.log("标签内容1:{}", text);
WebElement delayElementId2 = driver.findElement(By.id("delayElementId2"));
String text2 = delayElementId2.getText();
Console.log("标签内容2:{}", text);
//关闭浏览器
//driver.quit();
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
head>
<body>
<a id="testA" href="javascript:;">See an example alerta>
<button id="alertBtn">See an example alertbutton>
body>
<script src="G:\VsCode\开源\jquery-3.5.1\jquery-3.5.1.min.js">script>
<script>
$(function(){
$("#alertBtn").click(() => {
console.log("点击alertBtn")
});
$("#testA").click(() => {
//确定按钮
// alert("点击a标签")
//确定、取消按钮
// confirm("水电费第三方第三方confirm")
//可输入内容、确定、取消按钮
var content = prompt("神鼎飞丹砂发顺丰prompt弹框")
alert(`prompt手动输入的内容:${content}`)
})
setTimeout(() => {
$("body").append("延迟3秒后插入的节点内容
");
},3000)
setTimeout(() => {
$("body").append("延迟4秒后插入的节点内容
");
},4000)
})
script>
html>
/**
* 显式等待
*/
@Test
@SneakyThrows
public void test6() {
WebDriverManager.chromedriver().setup();
ChromeDriver driver = new ChromeDriver();
driver.get("C:\\Users\\Administrator\\Desktop\\index.html");
//针对全局有效,整个生命周期,在设置的超时时间范围内不断查找元素,直到5秒仍然找不到则报错
//driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
WebDriverWait webDriverWait = new WebDriverWait(driver, Duration.ofSeconds(5));
WebElement delayElementId = webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.id("delayElementId")));
//WebElement delayElementId = driver.findElement(By.id("delayElementId"));
String text = delayElementId.getText();
Console.log("标签内容:{}", text);
//这里会报错 == 不能立即找到元素
WebElement delayElementId2 = driver.findElement(By.id("delayElementId2"));
String text2 = delayElementId2.getText();
Console.log("标签内容2:{}", text);
//关闭浏览器
//driver.quit();
}
index.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>indextitle>
head>
<body>
<h1>第一个页面h1>
<a id="testA" href="javascript:;">See an example alerta>
<button id="alertBtn">See an example alertbutton>
<br/>
<a href="./index2.html" target="_blank">第二个页面a>
<br/>
<a href="./index3.html" target="_blank">第三个页面a>
body>
<script src="G:\VsCode\开源\jquery-3.5.1\jquery-3.5.1.min.js">script>
<script>
$(function(){
$("#alertBtn").click(() => {
console.log("点击alertBtn")
});
$("#testA").click(() => {
//确定按钮
// alert("点击a标签")
//确定、取消按钮
// confirm("水电费第三方第三方confirm")
//可输入内容、确定、取消按钮
var content = prompt("神鼎飞丹砂发顺丰prompt弹框")
alert(`prompt手动输入的内容:${content}`)
})
setTimeout(() => {
$("body").append("延迟3秒后插入的节点内容
");
},3000)
setTimeout(() => {
$("body").append("延迟4秒后插入的节点内容
");
},4000)
})
script>
html>
index2.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>index2title>
head>
<body>
<h1>第二个页面h1>
body>
<script src="G:\VsCode\开源\jquery-3.5.1\jquery-3.5.1.min.js">script>
<script>
script>
html>
index3.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>index3title>
head>
<body>
<h1>第三个页面h1>
body>
<script src="G:\VsCode\开源\jquery-3.5.1\jquery-3.5.1.min.js">script>
<script>
script>
html>
/**
* 显式等待
*/
@Test
@SneakyThrows
public void tabSwitchTest() {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("file:///C:/Users/Administrator/Desktop/index.html");
Console.log("【新开页面前】当前所在的Tab(窗口)标识:{}",driver.getWindowHandle());
Console.log("【新开页面前】当前共有的Tab(窗口)标识({}):{}\n",driver.getWindowHandles().size(),driver.getWindowHandles());
//新开两个Tab页,当前共有3个Tab
driver.findElement(By.linkText("第二个页面")).click();
driver.findElement(By.linkText("第三个页面")).click();
Console.log("【新开页面后】当前所在的Tab(窗口)标识:{}",driver.getWindowHandle());
Console.log("【新开页面后】当前共有的Tab(窗口)标识({}):{}\n",driver.getWindowHandles().size(),driver.getWindowHandles());
//切换到第三个页面
for (String windowHandle : driver.getWindowHandles()) {
String pageTitle = driver.switchTo().window(windowHandle).getTitle();
//根据页面的title节点进行切换
if(StrUtil.equals(pageTitle,"index3")) {
Console.log("Tabe切换成功:index3页面");
break;
}
}
Console.log("【切换页面后】当前所在的Tab(窗口)标识:{}",driver.getWindowHandle());
Console.log("【切换页面后】当前共有的Tab(窗口)标识({}):{}",driver.getWindowHandles().size(),driver.getWindowHandles());
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>index2title>
head>
<body>
<h1>第二个页面h1>
body>
<script src="G:\VsCode\开源\jquery-3.5.1\jquery-3.5.1.min.js">script>
<script>
script>
html>
/**
* select控件使用
*/
@Test
@SneakyThrows
public void jsPerformETest() {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("C:\\Users\\Administrator\\Desktop\\index2.html");
Thread.sleep(1000);
JavascriptExecutor javascriptExecutor = (JavascriptExecutor) driver;
javascriptExecutor.executeScript("$(\"body\").append(\"selenium自动化添加的JS执行
\");");
}
//去谷歌、edge浏览器的插件商场上找插件
selenium ide
//去火狐找
selenium ide
Katalon Recorder (Selenium tests generator)