使用 XPath (Selenium WebDriver) 点击 SVG 中的元素。

seleniumautomation testingtesting tools更新于 2026/2/5 8:37:17

我们可以使用 Selenium 中的 XPath 点击 SVG 中的元素。SVG 元素的标签名为 svg。它具有 width、height、viewBox 等属性。

要点击 SVG 元素,我们需要识别该元素,然后使用 Actions 类。我们首先使用 moveToElement 方法移动到该元素,然后对其应用 click 方法。

最后,要实际执行操作,我们必须使用 build 和 execute 方法。要使用 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://www.tutorialspoint.com/index.htm");
      // 等待 5 秒
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // 识别元素,输入文本
      WebElement m= driver.findElement(By.xpath ("//*[local-name()='svg' and @data-icon='home']/*[localname()='path']"));
      // 用于移动和点击元素的操作类
      Actions a = new Actions(driver);
      a.moveToElement(m).
      click().build().perform();
   }
}

输出


相关文章