如何使用 Selenium 中的屬性“HTML 標籤名稱”查詢元素?
藉助定位符標籤名,我們可以使用 Selenium 網頁驅動程式找到元素標籤名。要使用標籤名定位元素,我們必須使用 By.tagName 方法。
在 HTML 程式碼中,標籤名通常用 <> 括起來,例如,錨定標籤 <a> 表示頁面上的連結。輸入標籤表示文字框、複選框或單選按鈕。我們來看看一個元素的 HTML 程式碼,並嘗試透過其標籤名對其進行識別 −
在上圖中,文字“You are browsing the best resources for”具有 h4 標籤。
語法
WebElement e = driver. findElement(By.tagName("h4"));
示例
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 LocatorTagName{ 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/index.htm"); // identify element with tag name WebElement n = driver.findElement(By.tagName("h4")); //obtain text on element String s = n.getText(); System.out.println("Text on element is : " + s); driver.close(); } }
輸出
廣告