1. 程式人生 > >TestNG(四)查找元素

TestNG(四)查找元素

操作 imp sop 工程文件 返回 工程 css選擇器 new htm

重點:

一、八種方法查找元素

1、ID 一般是唯一的(By.id)

WebElement keyfind = driver.findElement(By.id("kw"));

2、name 使用是要確定當前打開頁面是否是唯一的,如果不是,那麽就會找打多個,無法進行操作。(By.name)

如何確定是否唯一?審查元素:Ctrl+F

3、鏈接文本

註意:只適應於a表標簽

4、部分鏈接文本

註意:只適應於a表標簽

5、通過tagname查找元素,很少用到。

6、xpath查找(By.xparh(xpath路徑))

7、CSS選取

原則:有ID用ID,但是ID可能是隨機數。沒有ID用name,如果name有重復,那麽就用xpath。

二、findElement與findElements 的區別

從字面上理解,findElement查找到一個元素,findElements查找到多個元素,並且都有返回值。

findElement 定義:WebElement findElement(By var1);

findElements定義:List<WebElement> findElements(By var1);

註意:使用findElement 當定位到多個的時候,findElement 只輸出第一個。

 @Test
public void findXparh02 (){
driver.get("https://www.baidu.com");
List<WebElement> list = driver.findElements(By.xpath("/html/body/div[1]/div[1]/div/div[3]/a[1]"));
// for (int i= 0; i<list.size() ; i++) {
//讀取文本
String text = list.get(0).getText();
//輸出文本
System.out.println(text);

}

三、常見錯誤

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"class name","selector":"mine-text"}

這種錯誤一般是元素值錯誤,重新看下元素定位的值是不是正確。

一 、利用ID查找元素

package test02;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestFindElements {
WebDriver driver;
@BeforeMethod
public void browesOpen(){
System.setProperty("Webdriver.chrome.driver","F:\\工程文件\\drivers\\MicrosoftWebDriver.exe");
driver = new ChromeDriver();
}
@Test
public void findElements(){
driver.get("https://www.baidu.com");
WebElement keyfind = driver.findElement(By.id("kw"));
}
@AfterMethod
public void browesclose(){
driver.quit();
}



}

二、name查找元素
例2

@Test
public void findNameElements() {
driver.get("https://www.baidu.com");
WebElement keyfind = driver.findElement(By.name("wd"));
}


六、xpath獲取元素
谷歌和火狐瀏覽器,先抓取你要的元素,然後右鍵copy-->copy xpath ;直接在代碼中粘貼就可以了。
@Test
public void findxpath (){
driver.get("https://www.baidu.com");
WebElement keyfind = driver.findElement(By.xpath("//*[@id=\"su\"]"));

七、通過CSS查找
谷歌瀏覽器,先抓取你要的元素,然後右鍵copy-->copy selector ;直接在代碼中粘貼就可以了。
火狐瀏覽器,先抓取你要的元素,然後右鍵copy-->CSS選擇器;直接在代碼中粘貼就可以了。
@Test
public void findCSS (){
driver.get("https://www.baidu.com");
WebElement keyfind = driver.findElement(By.cssSelector("#su"));
}


















TestNG(四)查找元素