Yoiku
Yoiku

Reputation: 912

Selenium preceding-sibling::text() not working

I am having issues with selenium using the next xpath "./preceding-sibling::text()" I don't understand why, my first thought was that IE wasn't supporting that xpath statement but it didnt work on chrome neither.

What I am trying to do is to verify if a radio button have a certain text "near" it. For example if a radio button is like this

<div>
  <label> Yes <input name='radioBtn'></input></label>
  <label> No <input name='radioBtn'></input></label>
</div>

This is a simplified scenario where I need to check the "yes" radio button, so what I am doing is to search for the radiobutton and check if it preceding-sibling::text(), but selenium is cant find any element. I know the Xpath works because I test it on chrome developer tools and it returns the text "Yes".

I can't do something like 'input[1]' because I can't be sure that the first one will be always that have the Yes text.

Any idea why isn't this working on selenium? and if there is any work around?

Upvotes: 0

Views: 1297

Answers (1)

Yoiku
Yoiku

Reputation: 912

I got to a work around but is kind of specific to the problem. But let's answer the questions 1 at the time.

  1. Any idea why isn't this working on selenium?

It's not working because selenium don't support text elements, so even when selenium find the element it cant map it to a selenium object, i didn't see it because my code hided the selenium exception. The Exception throw is the next one:

An unhandled exception of type 'OpenQA.Selenium.InvalidSelectorException' occurred in WebDriver.dll

Additional information: invalid selector: The result of the xpath expression "./preceding-sibling::text()" is: [object Text]. It should be an element

  1. Is there any work around?

Yes it is. What I did was to run a java script using the selenium IJavaScriptExecutor. With the script I revised the preceding sibling text and return it as a string so if the text was equal to the thing I was looking for (i.e Yes) trhat means that is the radio button I was looking for. The code looks is similar to this (it can have some sintax errors since I didn't copied from the source):

string script =  "function GetPrecedingText(node){"+
"var result = document.evaluate('./preceding-sibling::text()[1]', node, null, XPathResult.STRING_TYPE, null);"+
"return (result==null) ? '' : result.stringValue.trim();}"+
"return GetPrecedingText(arguments[0])";

string result = ((driver as IJavaScriptExecutor).ExecuteScript(script, SeleniumElement)).toString();

Hope someone can find this useful :) and thanks for all that tried to help me :)

Upvotes: 1

Related Questions