0

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.

TabooSheen
  • 13
  • 2
  • 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 Mar 22 '17 at 01:28
  • [`element.getAttribute("textContent")`](http://stackoverflow.com/questions/20888592/gettext-method-of-selenium-chrome-driver-sometimes-returns-an-empty-string) ? – har07 Mar 22 '17 at 09:08
  • @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: value 1 value 2 – TabooSheen Mar 22 '17 at 18:05
  • @har07 getAttribute works! – TabooSheen Mar 22 '17 at 18:17
  • Are you trying to pull the text from each of the `` elements or just a specific one? Here are some CSS selector references: https://www.w3.org/TR/selectors/#selectors, https://saucelabs.com/resources/articles/selenium-tips-css-selectors. – JeffC Mar 22 '17 at 18:29
  • @JeffC Thanks! I found what I was looking for in [class='text-class'] and :nth-child(n) selectors. – TabooSheen Mar 22 '17 at 20:48
  • Great. I posted my comments as an answer. If you would, please mark it as accepted since you found your answer and upvote it if you found it useful. Thanks! – JeffC Mar 22 '17 at 21:03

1 Answers1

0

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

JeffC
  • 22,180
  • 5
  • 32
  • 55