在Selenium 的findElement()和findElements()方法通過webdriver和WebElement類提供的幫助進行webdriver定位元素。
findElement()方法返回一個基于指定的搜索條件WebElement對象或最終拋出一個異常,如果沒有找到符合搜索條件的任何元素。
findElements()方法返回WebElements符合搜索條件的列表。如果沒有發(fā)現(xiàn)的元素,則返回空列表。
下表給出了定位selenium 元素的webdriver的Java語法。
| Method | Syntax | 描述 |
|---|---|---|
| By ID | driver.findElement(By.id(<element ID>)) | 定位元素使用ID屬性 |
| By name | driver.findElement(By.name(<element name>)) | 定位使用Name屬性的元素 |
| By class name | driver.findElement(By.className(<element class>)) | 定位使用類屬性的元素 |
| By tag name | driver.findElement(By.tagName(<htmltagname>)) | 定位使用HTML標記元素 |
| By link text | driver.findElement(By.linkText(<linktext>)) | 定位使用的鏈接文字鏈接 |
| By partial link text | driver.findElement(By.partialLinkText(<linktext>)) | 定位鏈接使用鏈接的文字部分 |
| By CSS | driver.findElement(By.cssSelector(<css selector>)) | 定位使用CSS選擇器的元素 |
| By XPath | driver.findElement(By.xpath(<xpath>)) | 定位使用XPath查詢元素 |
現(xiàn)在讓我們了解這些定位器方法每個人的實際使用情況與http://www.calculator.net幫助
1,根據(jù)ID:對象訪問使用ID的幫助。在這種情況下,它是文本框的ID。該值使用SendKeys方法與ID(cdensity)的幫助下進入文本。
driver.findElement(By.id("cdensity")).sendKeys("10");
2,按名稱:訪問對象時使用的名稱的幫助。在這種情況下,它是文本框的名稱。該值是使用SendKeys方法與ID(cdensity)的幫助下進入文本。
driver.findElement(By.name("cdensity")).sendKeys("10");
3,通過類名:對象與類的名稱,幫助進行訪問。在這種情況下,它是WebElement的類名。該值可以用gettext方法進行訪問。
List<WebElement> byclass = driver.findElements(By.className("smalltext smtb"));
4,通過標簽名:元素的DOM標簽名稱,這是很容易處理的表使用此方法。我們可以看一個例子了演示程序。
WebElement table = driver.findElement(By.id("calctable"));
List<WebElement> row = table.findElements(By.tagName("tr"));
int rowcount = row.size();
5,通過鏈接文本:此方法可以幫助我們找到與之相配的可見文本的鏈接元素。
driver.findElements(By.linkText("Volume")).click();
5,通過部分鏈接文本:此方法可以幫助我們找到了部分匹配可見文本的鏈接元素。
driver.findElements(By.partialLinkText("Volume")).click();
6,使用CSS:CSS的使用作為一種方法來識別網(wǎng)絡對象,但不是所有的瀏覽器支持CSS標識。
WebElement loginButton = driver.findElement(By.cssSelector("input.login"));
7,通過Xpath:XML表示XML路徑語言,是一種查詢語言,用于從XML文檔中選擇節(jié)點。 XPath語言是基于XML文檔的樹表示,并提供選擇使用各種標準的節(jié)點來瀏覽周圍的樹。
driver.findElement(By.xpath(".//*[@id='content']/table[1]/tbody/tr/td/table/tbody/tr[2]/td[1]/input")).sendkeys("100");