Selenium WebDriver: clicking on elements within an SVG using XPath Selenium WebDriver: clicking on elements within an SVG using XPath selenium selenium

Selenium WebDriver: clicking on elements within an SVG using XPath


For anyone interested, I solved this in the following ways:

1) I was originally testing this on OSX with Firefox 17 and Selenium 2.28/29, but figured out it only works (at least for me) on Windows with Firefox 18 and Selenium 2.29

2) interacting with SVGs with the standard:

driver.findElement(By.xpath(YOUR XPATH)).click();

doesn't work. You need to use Actions.

3) to interact with SVG objects, the following XPath works:

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

The SVG object being anything under the SVG element (e.g. circle, rect, text, etc).

An example of clicking an SVG object:

WebElement svgObject = driver.findElement(By.xpath(YOUR XPATH));Actions builder = new Actions(driver);builder.click(svgObject).build().perform();

Note: you need to call the path inside the click() function; using:

moveToElement(YOUR XPATH).click().build().perform();

doesn't work.


Try this workaround :

WebElement mapObject = driver.findElement(By.xpath("//*[name()='svg']/*[name()='rect']"));((JavascriptExecutor) driver).executeScript("arguments[0].click();", mapObject);

Whenever I have too many problems with some elements while trying to click them, I use this workaround.


We were able to avoid the odd xpath select by doing these two things

WebElement mapObject = (WebElement) driver.executeScript('return document.querySelector(arguments[0])', "svg rect")((JavascriptExecutor) driver).executeScript("arguments[0].dispatchEvent(new MouseEvent('click', {view: window, bubbles:true, cancelable: true}))", mapObject);

This worked on osx and phantomjs but I think it should be ok in any modern browser.

(We used the js driver so feel free to fix any compile errors)