0
votes

I am trying to capture and store some text that appears inside of an svg element such as

<svg>
   <g>
      <text>Value to get</text>
   </g>
</svg>

I have a method that I am using and it works for other elements, but the Selenium WebElement class method getText does not return any text for an svg element such as above.

Here is what my xpath looks like for the above example

//*[local-name()='g']//*[local-name()='text']

I am able to use findElement(By.xpath(myXpath)), but then when I call .getText() on it, it does not return any value and it also does not throw any errors.

Is there something I am doing wrong, or possibly an alternative method?

Also something interesting to note, the above approach worked fine on a Windows 7 machine, but not on Mac.

1
Have you tried something simple like a CSS selector, driver.findElement(By.cssSelector("svg > g > text")).getText();? Have you checked to see how many matches there are on the page? Perhaps the first match that you are getting actually has no text inside. Open the Chrome dev console and type $$("svg > g > text").length and see if it returns more than 1. - JeffC
@JeffC, I have not used cssSelector before, but I can give it a try. How can I uniquely get an element if there are multiple text elements in my original example such as: <g> <text class='text-class'> value 1 </text> <text class='text-class'> value 2 </text> <g> - TabooSheen
@har07 getAttribute works! - TabooSheen
Are you trying to pull the text from each of the <text> elements or just a specific one? Here are some CSS selector references: w3.org/TR/selectors/#selectors, saucelabs.com/resources/articles/selenium-tips-css-selectors. - JeffC

1 Answers

0
votes

Have you tried something simple like a CSS selector, driver.findElement(By.cssSelector("svg > g > text")).getText();? Have you checked to see how many matches there are on the page? Perhaps the first match that you are getting actually has no text inside. Open the Chrome dev console and type $$("svg > g > text").length and see if it returns more than 1.

Here are some CSS selector references:

CSS Selectors Reference

CSS Selector Tips