SeleniumUtils工具类提交

This commit is contained in:
温在好
2025-04-22 20:07:29 +08:00
parent 4babf44054
commit 953b06a9bc

View File

@@ -0,0 +1,381 @@
package com.test.common.utils;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
import java.util.List;
import java.util.Set;
/**
* Selenium 工具类
*/
public class SeleniumUtils {
private WebDriver driver;
private WebDriverWait wait;
private Actions actions;
// 构造函数
public SeleniumUtils(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver, Duration.ofSeconds(10));
this.actions = new Actions(driver);
}
// 设置显式等待超时时间
public void setWaitTimeout(long seconds) {
this.wait = new WebDriverWait(driver, Duration.ofSeconds(seconds));
}
// 打开URL
public void openUrl(String url) {
driver.get(url);
}
// 获取当前URL
public String getCurrentUrl() {
return driver.getCurrentUrl();
}
// 获取页面标题
public String getPageTitle() {
return driver.getTitle();
}
// 通过ID查找元素
public WebElement findElementById(String id) {
return wait.until(ExpectedConditions.presenceOfElementLocated(By.id(id)));
}
// 通过name查找元素
public WebElement findElementByName(String name) {
return wait.until(ExpectedConditions.presenceOfElementLocated(By.name(name)));
}
// 通过className查找元素
public WebElement findElementByClassName(String className) {
return wait.until(ExpectedConditions.presenceOfElementLocated(By.className(className)));
}
// 通过xpath查找元素
public WebElement findElementByXpath(String xpath) {
return wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
}
// 通过cssSelector查找元素
public WebElement findElementByCssSelector(String cssSelector) {
return wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(cssSelector)));
}
// 通过linkText查找元素
public WebElement findElementByLinkText(String linkText) {
return wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText(linkText)));
}
// 通过partialLinkText查找元素
public WebElement findElementByPartialLinkText(String partialLinkText) {
return wait.until(ExpectedConditions.presenceOfElementLocated(By.partialLinkText(partialLinkText)));
}
// 通过tagName查找元素
public WebElement findElementByTagName(String tagName) {
return wait.until(ExpectedConditions.presenceOfElementLocated(By.tagName(tagName)));
}
// 查找多个元素
public List<WebElement> findElements(By by) {
return wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(by));
}
// 输入文本
public void sendKeys(WebElement element, String text) {
wait.until(ExpectedConditions.visibilityOf(element)).clear();
element.sendKeys(text);
}
// 点击元素
public void click(WebElement element) {
wait.until(ExpectedConditions.elementToBeClickable(element)).click();
}
// 获取元素文本
public String getText(WebElement element) {
return wait.until(ExpectedConditions.visibilityOf(element)).getText();
}
// 获取元素属性值
public String getAttribute(WebElement element, String attribute) {
return wait.until(ExpectedConditions.visibilityOf(element)).getAttribute(attribute);
}
// 判断元素是否显示
public boolean isDisplayed(WebElement element) {
try {
return element.isDisplayed();
} catch (NoSuchElementException e) {
return false;
}
}
// 判断元素是否启用
public boolean isEnabled(WebElement element) {
try {
return element.isEnabled();
} catch (NoSuchElementException e) {
return false;
}
}
// 判断元素是否被选中
public boolean isSelected(WebElement element) {
try {
return element.isSelected();
} catch (NoSuchElementException e) {
return false;
}
}
// 选择下拉框选项(通过value)
public void selectByValue(WebElement element, String value) {
new Select(wait.until(ExpectedConditions.visibilityOf(element))).selectByValue(value);
}
// 选择下拉框选项(通过visible text)
public void selectByVisibleText(WebElement element, String text) {
new Select(wait.until(ExpectedConditions.visibilityOf(element))).selectByVisibleText(text);
}
// 选择下拉框选项(通过index)
public void selectByIndex(WebElement element, int index) {
new Select(wait.until(ExpectedConditions.visibilityOf(element))).selectByIndex(index);
}
// 获取下拉框所有选项
public List<WebElement> getSelectOptions(WebElement element) {
return new Select(element).getOptions();
}
// 获取选中的下拉框选项
public WebElement getFirstSelectedOption(WebElement element) {
return new Select(element).getFirstSelectedOption();
}
// 鼠标悬停
public void mouseHover(WebElement element) {
actions.moveToElement(wait.until(ExpectedConditions.visibilityOf(element))).perform();
}
// 鼠标双击
public void doubleClick(WebElement element) {
actions.doubleClick(wait.until(ExpectedConditions.visibilityOf(element))).perform();
}
// 鼠标右键点击
public void contextClick(WebElement element) {
actions.contextClick(wait.until(ExpectedConditions.visibilityOf(element))).perform();
}
// 拖拽元素
public void dragAndDrop(WebElement source, WebElement target) {
actions.dragAndDrop(
wait.until(ExpectedConditions.visibilityOf(source)),
wait.until(ExpectedConditions.visibilityOf(target))
).perform();
}
// 执行JavaScript
public Object executeScript(String script, Object... args) {
JavascriptExecutor js = (JavascriptExecutor) driver;
return js.executeScript(script, args);
}
// 滚动到元素可见
public void scrollToElement(WebElement element) {
executeScript("arguments[0].scrollIntoView(true);", element);
}
// 滚动到页面底部
public void scrollToBottom() {
executeScript("window.scrollTo(0, document.body.scrollHeight)");
}
// 滚动到页面顶部
public void scrollToTop() {
executeScript("window.scrollTo(0, 0)");
}
// 切换到frame
public void switchToFrame(WebElement frameElement) {
driver.switchTo().frame(frameElement);
}
// 切换到主窗口
public void switchToDefaultContent() {
driver.switchTo().defaultContent();
}
// 切换到父frame
public void switchToParentFrame() {
driver.switchTo().parentFrame();
}
// 切换到alert
public Alert switchToAlert() {
return wait.until(ExpectedConditions.alertIsPresent());
}
// 接受alert
public void acceptAlert() {
switchToAlert().accept();
}
// 取消alert
public void dismissAlert() {
switchToAlert().dismiss();
}
// 获取alert文本
public String getAlertText() {
return switchToAlert().getText();
}
// 在alert中输入文本
public void sendKeysToAlert(String text) {
switchToAlert().sendKeys(text);
}
// 切换到窗口
public void switchToWindow(String windowHandle) {
driver.switchTo().window(windowHandle);
}
// 获取当前窗口句柄
public String getCurrentWindowHandle() {
return driver.getWindowHandle();
}
// 获取所有窗口句柄
public Set<String> getAllWindowHandles() {
return driver.getWindowHandles();
}
// 关闭当前窗口
public void closeCurrentWindow() {
driver.close();
}
// 刷新页面
public void refreshPage() {
driver.navigate().refresh();
}
// 前进
public void navigateForward() {
driver.navigate().forward();
}
// 后退
public void navigateBack() {
driver.navigate().back();
}
// 获取页面源码
public String getPageSource() {
return driver.getPageSource();
}
// 设置窗口大小
public void setWindowSize(int width, int height) {
driver.manage().window().setSize(new Dimension(width, height));
}
// 最大化窗口
public void maximizeWindow() {
driver.manage().window().maximize();
}
// 全屏窗口
public void fullscreenWindow() {
driver.manage().window().fullscreen();
}
// 获取cookie
public Set<Cookie> getCookies() {
return driver.manage().getCookies();
}
// 获取指定cookie
public Cookie getCookieNamed(String name) {
return driver.manage().getCookieNamed(name);
}
// 添加cookie
public void addCookie(Cookie cookie) {
driver.manage().addCookie(cookie);
}
// 删除cookie
public void deleteCookie(Cookie cookie) {
driver.manage().deleteCookie(cookie);
}
// 删除指定cookie
public void deleteCookieNamed(String name) {
driver.manage().deleteCookieNamed(name);
}
// 删除所有cookie
public void deleteAllCookies() {
driver.manage().deleteAllCookies();
}
// 等待元素可见
public void waitForElementVisible(By by, long timeoutInSeconds) {
new WebDriverWait(driver, Duration.ofSeconds(timeoutInSeconds))
.until(ExpectedConditions.visibilityOfElementLocated(by));
}
// 等待元素可点击
public void waitForElementClickable(By by, long timeoutInSeconds) {
new WebDriverWait(driver, Duration.ofSeconds(timeoutInSeconds))
.until(ExpectedConditions.elementToBeClickable(by));
}
// 等待元素消失
public void waitForElementInvisible(By by, long timeoutInSeconds) {
new WebDriverWait(driver, Duration.ofSeconds(timeoutInSeconds))
.until(ExpectedConditions.invisibilityOfElementLocated(by));
}
// 等待文本出现在元素中
public void waitForTextPresentInElement(By by, String text, long timeoutInSeconds) {
new WebDriverWait(driver, Duration.ofSeconds(timeoutInSeconds))
.until(ExpectedConditions.textToBePresentInElementLocated(by, text));
}
// 截屏并保存为Base64
public String takeScreenshotAsBase64() {
return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);
}
// 截屏并保存为字节数组
public byte[] takeScreenshotAsBytes() {
return ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
}
// 截屏并保存为文件
public String takeScreenshotAsFile(String filePath) {
return ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE).getAbsolutePath();
}
// 关闭浏览器
public void quit() {
if (driver != null) {
driver.quit();
}
}
}