如何在Selenium WebDriver中使用xPath来获取SVG元素?

我正在使用Selenium WebDriver (Java版)测试基于OpenLayers的API。

我想测试一个使用OpenLayers .Control.ModifyFeature的function。 我想点击绘制的特征(SVG),然后拖动并检查它们是否存在,可见或隐藏。

我画了一个多边形,我选择了它。 见下图:

polygon_and_handles

这些SVG元素的HTML在这里:

               

假设我想选择红点。

我这样做了:

 String xpath = "//circle[contains(@id, 'OpenLayers_Geometry_Point') AND fill = '#990000']"; List vertices = driver.findElements(By.xpath(xpath)); 

但它总是返回一个空列表[]

我在这做错了什么? 请问有人帮帮我吗?

非常感谢。

编辑1 – function:verticesAreVisible

在单击操作之前,我想获取元素并检查它们是否可见。 我正在使用这个function。

 public static boolean verticesAreVisible(WebDriver driver, String xpath) { List list = driver.findElements(By.xpath(xpath)); if (list.isEmpty()) { return false; } boolean visible = true; for (int i = 0; i < list.size(); i++) { visible = visible && list.get(i).isDisplayed(); } return !verticesAreNotVisible(driver) && visible; } 

编辑2 – 纠正xPath

 // This solution from Razib is valid if the SVG is on the root note String xpath = "/*[name()='svg']/*[name()='circle']"; // I changed it so that any descendant is valid "//" String xpath = "//*[name()='svg']//*[name()='circle']"; // Since I wanted only the red vertices, I added this String xpath = "//*[name()='svg']//*[name()='circle' and @fill='#990000']"; 

可能需要在Xpath使用Actions with name属性。 在你的XPath中使用它 –

 "/*[name()='svg']/*[name()='SVG OBJECT']" 

然后尝试以下代码片段 –

 WebElement svgObj = driver.findElement(By.xpath(XPATH)); Actions actionBuilder = new Actions(driver); actionBuilder.click(svgObj).build().perform(); 

尝试@fill而不是fillOpenLayers_Geometry_Point而不是OpenLayers.Geometry.Point

要获得只有visibile元素,您可以使用:

 wait = new WebDriverWait(driver, 5); wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("bla bla"))); 
  We also faced the similar issue in one of the screens where we have SVG implementation, I resolved using action class. Action Class Package : java.lang.Object org.openqa.selenium.interactions.Actions Sample Code : WebElement svgObject= driver.findElement(By.xpath(XPATH)); Actions actionBuilderObj = new Actions(driver); actionBuilderObj .click(svgObject).build().perform();