How to use xPath in Selenium WebDriver to grab SVG elements?
May be you need to use the Actions with name
attribute in Xpath
.
In your XPath use it -
"/*[name()='svg']/*[name()='SVG OBJECT']"
Then try the following code snippet -
WebElement svgObj = driver.findElement(By.xpath(XPATH));
Actions actionBuilder = new Actions(driver);
actionBuilder.click(svgObj).build().perform();
To locate the red points i.e. the elements with attribute fill="#990000"
and id attribute containing OpenLayers_Geometry_Point you can use either of the following Locator Strategies:
Using xpath:
//*[name()='svg']/*[name()='g']/*[name()='g']//*[name()='circle' and contains(@fill, '990000')][starts-with(@id, 'OpenLayers_Geometry_Point')]
Using css-selectors:
svg > g > g circle[fill$='990000'][id^='OpenLayers_Geometry_Point']
Ideally, you need to induce WebDriverWait for the visibilityOfAllElementsLocatedBy()
and you can use either of the following Locator Strategies:
Using cssSelector:
List<WebElement> vertices = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("svg > g > g circle[fill$='990000'][id^='OpenLayers_Geometry_Point']")));
Using xpath:
List<WebElement> vertices = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//*[name()='svg']/*[name()='g']/*[name()='g']//*[name()='circle' and contains(@fill, '990000')][starts-with(@id, 'OpenLayers_Geometry_Point')]")));
References
You can find a couple of relevant details discussions in:
- How to click on SVG elements using XPath and Selenium WebDriver through Java
- Clicking on svg using selenium python
- Unable to locate SVG elements through xpath on Kendo UI chart
- Creating XPATH for svg tag
- How to access to 'rect' type element through Selenium-Python