如何在 Selenium WebDriver 中使用 XPath 獲取 SVG 元素?
我們可以使用 xpath 來使用 Selenium Webdriver 獲取 SVG 元素。SVG 元素用標籤名 **svg** 識別。svg 影像具有諸如 *width* 和 *height* 等屬性。
讓我們研究一下 svg 元素的 html 程式碼。
要為 svg 元素建立 xpath,語法為 **//*[local-name()='svg']**。
local-name 函式對於建立 svg 元素的 xpath 是必須的。因此,上面影像中突出顯示的影像的 xpath 表示式應為 -
//*[local-name()='svg' and @data-icon='home']/*[local-name()='path']
這裡,**data-icon** 是 svg 標籤元素的一個屬性,它與 @ 符號一起新增。[local-name()='path'] 包含在內,因為它是的 svg 標籤名的子元素。
讓我們在 Console 選項卡中驗證我們建立的 xpath。
主頁選單之前的 SVG 元素影像將使用我們的 XPath 突出顯示。
示例
程式碼實現。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class SVGElement{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); // wait of 5 seconds driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://tutorialspoint.tw/index.htm"); // identify element WebElement m= driver.findElement(By.xpath("//*[local-name()='svg' and @dataicon='home']/*[local-name()='path']")); // Action class to move and click element Actions act = new Actions(driver); act.moveToElement(m). click().build().perform(); driver.quit(); } }
廣告