9.selenium之定位一組元素
阿新 • • 發佈:2020-08-26
我們已經學習了8種定位方法, 那8種定位方法是針對單個元素定位的, WebDriver還提供了另外8種用於定位一組元素的方法。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.Keys; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterTest; importorg.testng.annotations.Test; findElements(By.id()) findElements(By.name()) findElements(By.className()) findElements(By.tagName()) findElements(By.linkText()) findElements(By.partialLinkText()) findElements(By.xpath()) findElements(By.cssSelector())
定位一組元素的方法與定位單個元素的方法類似,唯一的區別是在單詞 findElement 後面多了一個 s 表示複數。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.List; public class ElementsDemo { public static void main(String[] args) throws InterruptedException { WebDriver driver= new ChromeDriver(); driver.get("https://www.baidu.com/"); WebElement search_text = driver.findElement(By.id("kw")); search_text.sendKeys("selenium"); search_text.submit(); Thread.sleep(2000); //匹配第一頁搜尋結果的標題, 迴圈列印 List<WebElement> search_result = driver.findElements(By.xpath("//div/div/h3")); //列印元素的個數 System.out.println(search_result.size()); // 迴圈列印搜尋結果的標題 for(WebElement result : search_result){ System.out.println(result.getText()); } System.out.println("-------我是分割線---------"); //列印第n結果的標題 WebElement text = search_result.get(search_result.size() - 10); System.out.println(text.getText()); driver.quit(); } }
結果如下:
12
selenium__軟體測試培訓_免費領取試聽課程
自動化測試工具selenium-新手入門寶典-實戰性強
Selenium(WEB自動化工具)_百度百科
Selenium automates browsers. That's it!官方
selenium安裝一款任何網站都能抓取的爬蟲工具
selenium庫的基本使用 - 簡書
selenium中文網 | selenium安裝、selenium使用、selenium中文...
Python Selenium庫的使用_凱耐的部落格-CSDN部落格_selenium
selenium_百度翻譯
selenium用法詳解_天涯笨熊的部落格-CSDN部落格_selenium
GitHub - SeleniumHQ/selenium: A browser automation framework...
Selenium Projects
-------我是分割線---------
Selenium(WEB自動化工具)_百度百科