1

I have an svg element with multiple g tags inside it. Typically, when I select a tag by name, I get a list of all tags on the page. For example, this returns a list of Selenium WebElement instances:

browser.find_elements_by_xpath('//a')

But when I try to select all the g tags inside my svg element, I only get the first element returned. For example:

browser.find_element_by_xpath('//*[name()="svg"]/*[name()="g"]')

And here my markup:

<svg xmlns="http://www.w3.org/2000/svg">
    <g>...</g>
    <g>...</g>
    <g>...</g>
    ...
</svg>

How can I select all the g tags?

jds
  • 7,910
  • 11
  • 63
  • 101

2 Answers2

2

That because you used find_element_by_xpath which returns the first element. To return all the elements then use find_elements_by_xpath:

browser.find_elements_by_xpath('//*[name()="svg"]/*[name()="g"]')

But I would use a CSS selector which is shorter:

browser.find_elements_by_css_selector('svg > g')
Florent B.
  • 41,537
  • 7
  • 86
  • 101
-1

Here is how I would do it:

With the following XML:

...
<svg>
    <g>1</g>
    <g>2</g>
    <g>3</g>
</svg>
...

Then use this XPath expression:

 //svg/g

This will return 3 nodes, as shown on this site: http://www.freeformatter.com/xpath-tester.html

NOTE1: If you introduce the namespace on the svg tag, you will see this error from the above site: The default (no prefix) Namespace URI for XPath queries is always '' and it cannot be redefined to 'http://www.w3.org/2000/svg'.

NOTE2: Another similar question here: XPath Error - The default (no prefix) Namespace URI for XPath queries is always ''

Community
  • 1
  • 1
djangofan
  • 28,471
  • 61
  • 196
  • 289
  • That XPath expression was the first one I tried, but it did not return any elements. I got the `name()="svg"` snippet from https://stackoverflow.com/questions/14592213/ – jds Apr 11 '16 at 20:51