如何在 Selenium 中使用“連結文字/部分連結文字”查詢元素?
我們可以在 Selenium webdriver 中使用連結文字或部分連結文字來查詢元素。這兩個定位器都只能應用於使用錨標記的元素。
連結文字定位器與錨標記內的文字匹配。部分連結文字定位器與錨標記內的文字部分匹配。如果找不到匹配的元素,這兩個定位器都將引發 NoSuchElementException。
語法
WebElement n =driver.findElement(By.partialLinkText("Coding")); WebElement l =driver.findElement(By.linkText("Coding Ground"));
讓我們找到頁面上突出顯示的元素 CODING GROUND -
示例
使用 linkText 實現程式碼
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class LnkTxt{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://tutorialspoint.tw/online_dev_tools.htm"); // identify element with link text WebElement n =driver.findElement(By.linkText("CODING GROUND")); n.click(); System.out.println("Current page title : " + driver.getTitle()); driver.quit(); } }
使用 partialLinkText 實現程式碼
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class PartialLnkTxt{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://tutorialspoint.tw/online_dev_tools.htm"); // identify element with partial link text WebElement m = driver.findElement(By.partialLinkText("CODING")); m.click(); System.out.println("Current page title : " + driver.getTitle()); driver.quit(); } }
輸出
廣告