1.元素的定位
web自動化測試的操作核心是能夠找到頁面對應的元素,然后才能對元素進行具體的操作。
常見的元素定位方式非常多,如id,classname,tagname,xpath,cssSelector
常用的主要由cssSelector和xpath
1.1 cssSelector選擇器
選擇器的功能:選中頁面中指定的標簽元素
選擇器的種類分為基礎選擇器和復合選擇器,常見的元素定位方式可以通過id選擇器和子類選擇器來進行定位。
selector選擇器
xpath
XML路徑語言,不僅可以在XML文件中查找信息,還可以在HTML中選取節點。
xpath使用路徑表達式來選擇xml文檔中的節點
xpath語法中:
xpath://*[@id=“kw”]
1.2.1 獲取HTML頁面所有的節點
//*
1.2.2 獲取HTML頁面指定的節點
//[指定節點]
//ul:獲取HTML頁面所有的ul節點
//input:獲取HTML頁面所有的input節點
1.2.3 獲取一個節點中的直接子節點
/
//span/input
1.2.4 獲取一個節點的父節點
//input/…獲取input節點的父節點
1.2.5實現節點屬性的匹配
[@…]
//*[@id=‘kw’]匹配HTML頁面中id屬性為kw的節點
1.2.6 使用指定索引的方式獲取對應的節點內容
注意:xpath的索引是從1開始的。
百度熱搜xpath定位://*[@id=“s-hotsearch-wrapper”]/div
更便捷的生成selector/xpath的方式:右鍵選擇復制"Copy selector/xpath"
沒有這樣的元素
注意:登錄狀態下和非登錄狀態下自動化打開的頁面不一定相同,因為在做自動化測試一定要注意頁面狀態的一致性NoSuchElementException找不到元素異常
findElement(By) 在頁面查找元素,返回值Element
findElements(By) 在頁面查找元素,返回值為List
2.操作測試對象
獲取到了頁面的元素之后,接下來就是要對元素進行操作了。常見的操作有點擊、提交、輸入、清除、獲取文本。
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.chrome.ChromeOptions;public class SeleniumChromeTest {public static void main(String[] args) throws InterruptedException {// 設置 ChromeDriver 的路徑String chromeDriverPath = "D:\\網頁下載\\chromedriver-win64\\chromedriver-win64\\chromedriver.exe"; // 替換為你的 chromedriver 路徑System.setProperty("webdriver.chrome.driver", chromeDriverPath);// 配置 Chrome 瀏覽器選項ChromeOptions options = new ChromeOptions();options.addArguments("--remote-allow-origins=*"); // 解決某些版本的兼容性問題// 初始化 ChromeDriverWebDriver driver = new ChromeDriver(options);try {// 打開目標網頁driver.get("https://www.baidu.com");// 等待頁面加載完成Thread.sleep(2000);// 定位搜索框元素WebElement searchBox = driver.findElement(By.id("kw"));// 在搜索框中輸入內容searchBox.sendKeys("Selenium Java 自動化測試");// 定位“百度一下”按鈕WebElement searchButton = driver.findElement(By.id("su"));// 點擊按鈕提交搜索searchButton.click();// 等待搜索結果加載完成Thread.sleep(3000);// 輸出當前頁面的標題System.out.println("當前頁面標題: " + driver.getTitle());} catch (Exception e) {e.printStackTrace();} finally {// 關閉瀏覽器driver.quit();}}
}
2.1點擊/提交對象
click()
// 找到百度一下按鈕并點擊
driver.findElement(By.cssSelector(“#su”)).click();
除了按鈕之外,頁面的絕大多數元素都可以點擊
頁面隱藏的標簽、不可見的標簽就不能點擊。
第一步篩選:看標簽的屬性是否有hidden關鍵字
第二步:看每個標簽對應的樣式
2.2模擬按鍵輸入
sendKeys(“”)
driver.findElement(By.cssSelector(“#kw”)).sendKeys(“輸入文字”);
輸入框可以接收的內容都可以通過sendKeys發送過去
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.apache.commons.io.FileUtils;import java.io.File;
import java.time.Duration;
import java.util.List;public class FirstTest {WebDriver driver = null;void createDriver() {String chromeDriverPath = "D:\\網頁下載\\chromedriver-win64\\chromedriver-win64\\chromedriver.exe"; // 替換為你的 chromedriver 路徑System.setProperty("webdriver.chrome.driver", chromeDriverPath);// 增加瀏覽器配置:創建驅動對象要強制指定允許訪問所有的鏈接// 配置 Chrome 瀏覽器選項ChromeOptions options = new ChromeOptions();options.addArguments("--remote-allow-origins=*"); // 解決某些版本的兼容性問題// 初始化 ChromeDriverdriver = new ChromeDriver(options);}// 測試百度搜索關鍵字:迪麗熱巴void test01() throws InterruptedException {createDriver();try {// 2.輸入完整的網址: https://www.baidu.comdriver.get("https://www.baidu.com");WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));// 3.找到輸入框,并輸入關鍵詞:迪麗熱巴wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#kw"))).sendKeys("迪麗熱巴");// 4.找到百度一下按鈕,并點擊wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#su"))).click();} catch (Exception e) {e.printStackTrace();takeScreenshot();} finally {if (driver != null) {Thread.sleep(8000);// 5.關閉瀏覽器driver.quit();}}}private void takeScreenshot() {if (driver != null) {try {File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);FileUtils.copyFile(screenshot, new File("screenshot.png"));System.out.println("截圖已保存到 screenshot.png");} catch (Exception e) {e.printStackTrace();}}}// 元素的定位void test02() throws InterruptedException {createDriver();// 選擇器driver.findElement(By.cssSelector("#s-hotsearch-wrapper > div"));driver.findElement(By.xpath("//*[@id=\"s-hotsearch-wrapper\"]/div"));List<WebElement> ll = driver.findElements(By.cssSelector("#hotsearch-content-wrapper > li > a >span.title-content-title"));for (int i = 0; i < 10; i++) {// 獲取元素Ele對應的文本System.out.println(ll.get(i).getText());}driver.quit();}// 操作元素void test03() throws InterruptedException {createDriver();// WebElement ele = driver.findElement(By.cssSelector("#head_wrapper"));
// ele.click();try {// 打開目標網頁driver.get("https://www.baidu.com");// 等待頁面加載完成Thread.sleep(2000);// 這兩行代碼是上面的測試代碼
// WebElement ele = driver.findElement(By.cssSelector("#head_wrapper"));
// ele.click();// 定位搜索框元素WebElement searchBox = driver.findElement(By.id("kw"));// 在搜索框中輸入內容searchBox.sendKeys("Java語言");// 定位“百度一下”按鈕WebElement searchButton = driver.findElement(By.id("su"));// 點擊按鈕提交搜索searchButton.click();// 等待搜索結果加載完成Thread.sleep(3000);} catch (Exception e) {e.printStackTrace();} finally {// 關閉瀏覽器driver.quit();}}
}
2.3清除文本內容
輸入文本后又想換一個新的關鍵詞,這里就需要用到clear()
若想要在一個場景下更換多個關鍵詞,需要將前一個關鍵詞清除掉,若不清除,每次sendKeys將完成拼接的操作
void test03() throws InterruptedException {createDriver();// WebElement ele = driver.findElement(By.cssSelector("#head_wrapper"));
// ele.click();try {// 打開目標網頁driver.get("https://www.baidu.com");// 等待頁面加載完成Thread.sleep(2000);// 這兩行代碼是上面的測試代碼
// WebElement ele = driver.findElement(By.cssSelector("#head_wrapper"));
// ele.click();// 定位搜索框元素WebElement searchBox = driver.findElement(By.id("kw"));// 在搜索框中輸入內容searchBox.sendKeys("Java語言");Thread.sleep(2000);searchBox.clear();Thread.sleep(2000);searchBox.sendKeys("賞心悅目的圖片");// 定位“百度一下”按鈕WebElement searchButton = driver.findElement(By.id("su"));// 點擊按鈕提交搜索searchButton.click();// 等待搜索結果加載完成Thread.sleep(3000);} catch (Exception e) {e.printStackTrace();} finally {// 關閉瀏覽器driver.quit();}}
2.4獲取文本信息
如果判斷獲取到的元素對應的文本是否符合預期呢?獲取元素對應的文本并打印一下
獲取文本信息:getText()
為什么打印的txt為空?
因為"百度一下"是input標簽里的屬性值 getAttribute(String)
2.5獲取當前頁面標題和URL
getTitle()
getCurrentUrl()
3.窗口設置大小
1)窗口的大小設置
// 窗口最小化
driver.manage().window().minimize();
// 窗口最大化
driver.manage().window().maximize();
// 窗口全屏
driver.manage().window().fullscreen();
// 手動設置窗口大小
driver.manage().window().setSize(new Dimension(800, 600));
打開百度新聞(窗口的切換)
是兩個新聞標簽頁
1)獲取當前頁面句柄
driver.getWindowHandle();
2)獲取所有頁面句柄:
driver.getWindowHandles();
void test04() {createDriver();try {// 打開百度首頁driver.get("https://www.baidu.com");System.out.println("已打開百度首頁:" + driver.getTitle());// 顯式等待頁面加載完成WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));// 點擊“新聞”鏈接WebElement newsLink = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#s-top-left > a:nth-child(1)")));newsLink.click();System.out.println("已點擊新聞鏈接");// 獲取當前窗口句柄String curHandle = driver.getWindowHandle();System.out.println("當前窗口句柄為:" + curHandle);System.out.println("===============================================");// 獲取所有窗口句柄并切換到新窗口Set<String> allHandles = driver.getWindowHandles();for (String handle : allHandles) {if (!handle.equals(curHandle)) { // 使用 equals() 比較字符串driver.switchTo().window(handle);System.out.println("跳轉之后:" + driver.getTitle());// 顯式等待目標元素加載完成WebElement headlineTabs = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#headline-tabs > ul")));System.out.println("找到目標元素:" + headlineTabs.getText());break; // 切換到新窗口后退出循環}}} catch (Exception e) {e.printStackTrace();} finally {// 關閉瀏覽器if (driver != null) {driver.quit();}}
}