使用 XPath(Selenium WebDriver)单击 SVG 中的元素。
我们将讲述如何使用 XPath 在 Selenium 中单击 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://tutorialspoint.com/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();
}
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP