使用 XPath(Selenium WebDriver)單擊 SVG 中的元素。


我們將講述如何使用 XPath 在 Selenium 中單擊 SVG 中的元素。SVG 元素的標籤名稱是 svg。它具有 width、height、viewBox 等屬性。

要單擊具有 svg 的元素,我們應該識別元素,然後使用 Actions 類。我們將首先使用 movetoElement 方法移動到該元素,然後對其應用 click 方法。

最後,要實際執行操作,我們必須使用 buildexecute 方法。要使用 xpath 標識 svg 元素,可以使用 local-name() 函式。

讓我們看一下 svg 元素的 html 程式碼。

示例

程式碼實現。

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;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
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();
      driver.get("https://tutorialspoint.tw/index.htm");
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element, enter text
      WebElement m= driver.findElement(By.xpath ("//*[local-name()='svg' and @data-icon='home']/*[localname()='path']"));
      // Action class to move and click element
      Actions a = new Actions(driver);
      a.moveToElement(m).
      click().build().perform();
   }
}

輸出

更新日期: 2020 年 12 月 28 日

11K+ 瀏覽量

開啟您的 職業生涯

完成課程,獲得認證

開始
廣告