3

I met a problem when I try to get an attribute of one tag.

Here is the html code:

<rect x="66.5" y="43.5" width="26" height="13" fill="#86E067" stroke="#ffffff" stroke-width="1" class="highcharts-point "></rect>

Here is the xpath for that html:

//*[@id="highcharts-z14trt3-4"]/svg/g[6]/g[1]/rect[2]. 

I copied this xpath from Chrome directly,

I am trying to get the attribute height, and here is what I did:

WebElement test = driver.findElement(By.xpath("//*[starts-with(@id,'highcharts')]/svg/g[6]/g[1]/rect[2]"));

I cannot use tagName as there are many tags called rect. Meanwhile, I cannot use the exactly same XPath as the id is dynamic.

So the result is that selenium says cannot locate the element.

Is the way I try to locate this element wrong? Any suggestions?

  • 1
    If possible also post your exception text and the full HTML or a URL. – FDM Jun 8 '17 at 9:10
3

svg has a default namespace http://www.w3.org/2000/svg. You need to handle namespaces. Either with a prefix:

//*[starts-with(@id,'highcharts')]/svg:svg/svg:g[6]/svg:g[1]/svg:rect[2]

Or, with local-name():

//*[starts-with(@id,'highcharts')]/*[local-name() = 'svg']/*[local-name() = 'g'][6]/*[local-name() = 'g'][1]/*[local-name() = 'rect'][2]
2

Solution 1: Your XPath is not valid. You are missing a ' after the word highcharts.

Solution 2: You are using findElement. Can you try using an explicit wait for the element to become visible? If your implicit waiting time is 0, findElement immediately throws an exception (it doesn't retry) which is understandable if your rect isn't loaded already when your page is ready.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.