依赖
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.6.0</version>
</dependency>
代码如下:
package utils;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
public class LoginExample {
public static void main(String[] args) {
// 设置 ChromeDriver 路径(需要提前安装并配置好)
System.setProperty("webdriver.chrome.driver", "D:\\application\\chromedriver\\chromedriver.exe");
// 创建 WebDriver 对象
WebDriver driver = new ChromeDriver();
SeleniumTools seleniumTools = new SeleniumTools();
try {
// 打开目标网站
driver.get("http://IP:PORT/dolphinscheduler/ui/login");
// 这里需要停顿,加载元素
Thread.sleep(3000);
// 定位到登录表单中的输入框元素
WebElement username = driver.findElement(By.xpath("/html/body/div[1]/div/div/div[2]/div[2]/form/div[1]/div[1]/div/div[1]/div/input"));
WebElement password = driver.findElement(By.xpath("/html/body/div[1]/div/div/div[2]/div[2]/form/div[2]/div[1]/div/div[1]/div/input"));
// 在输入框中输入用户名和密码
username.sendKeys("username");
password.sendKeys("password");
// 点击登录按钮
clickButton(driver, "/html/body/div[1]/div/div/div[2]/div[2]/button");
driver.get("http://IP:PORT/dolphinscheduler/ui/projects/list");
Thread.sleep(3000);
WebElement inputProject = driver.findElement(By.xpath("/html/body/div[1]/div/div/div/div[2]/div/div/div/div[1]/div/div/div[1]/div/div/div/div[1]/div/div[1]/div[1]/input"));
inputProject.sendKeys("dddddddddddd");
// 输入dddddddddddd 搜索
clickButton(driver, "/html/body/div[1]/div/div/div/div[2]/div/div/div/div[1]/div/div/div[1]/div/div/div/div[2]/button");
// 点击搜索 按钮
clickButton(driver, "/html/body/div[1]/div/div/div/div[2]/div/div/div/div[1]/div/div/div[2]/div[2]/div[1]/div/div/div/div[1]/div/table/tbody/tr[2]/td[2]/button");
widthAndheight(driver);
// 获取当前页面的截图并保存为文件
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File("D:\\log\\dddddddd.jpg"));
// 输出截图文件路径
System.out.println("截图已保存到:" + screenshotFile.getAbsolutePath());
// 等待登录成功后的处理...
Thread.sleep(6000);
} catch (Exception e) {
e.printStackTrace();
} finally {
//close仅仅关闭了当前页面,并未关闭chrome。
//使用quit则会真正退出chrome,结束进程。
//两者一起使用,才能避免频繁的启动关闭出现的卡住现象(重点)
driver.close();
driver.quit();
}
}
public static void widthAndheight(WebDriver driver) {
//获取高度和宽度一定要在设置URL之后,不然会导致获取不到页面真实的宽高;
Long width = (Long) ((ChromeDriver) driver).executeScript("return document.documentElement.scrollWidth");
Long height = (Long) ((ChromeDriver) driver).executeScript("return document.documentElement.scrollHeight");
System.out.println("宽带:" + width);
System.out.println("高度:" + height);
}
//点击对应按钮
public static void clickButton(WebDriver driver, String xpth) throws Exception {
Thread.sleep(3000);
By searchButton = By.xpath(xpth);
driver.findElement(searchButton).click();
// 最大化窗口
driver.manage().window().maximize();
Thread.sleep(2000);
}
}