Selenium preceding-sibling::text() not working - selenium

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?

I got to a work around but is kind of specific to the problem. But let's answer the questions 1 at the time.
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
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 :)

Related

Unable to access the element in the frame

I am still dipping my toes in selenium , I am SAP guy working on Selenium automation POC. my requirement is to click on the drop down and select a value from the droplist.
I have extensively looked at the previous posts but could not find any answers. I have tried all the suggestions from the post but nothing seems to be working for me.
Please can you help me how to access this drop down value.
HTML code is attached in the pic along with the element that I am trying to access
My selenium code :
driver.switchTo().frame(driver.findElement(By.name("SMFrame")));
System.out.println("TExt" + driver.findElement(By.xpath("//div[#class='file-type']")).getText());
Error:
error -- > no such element: Unable to locate element: {"method":"xpath","selector":"//div[#class='file-type']"}
Image
Assuming you are correctly getting into the iframe
Right now you are selecting a div above the actual dropdown element (the select-dropdown tag). You may want to try changing your xpath to search for the tag like so:
//div[#class='file-dropdown']/select-dropdown
Also you should be creating a dropdown object like this. Then calling a method on it to select the dropdown option you are looking for:
Select dropdown = new Select(driver.findElement(By.xpath("//div[#class='file-dropdown']/select-dropdown");
System.out.println(dropdown.selectByVisibleText("text that you are looking for in the options"));
This is a good explanation of how to do it: https://www.javatpoint.com/selenium-webdriver-handling-drop-downs

element not visible Selenium capybara

I am getting below error while executing below capybara command,
The interesting thing is the same XPath is not giving any error in I am expecting that XPath to be present.
But when I am trying to perform click on that XPath, it's throwing below error.
--------------code----------------
Then(/^I click on "([^"])" on left tree child of "([^"])"$/) do |child, parent|
within(:xpath, ".//div/span[#class='folder-nav-tree-fileroom' and text()='DND-IndexTwistyExpClps']/../../../../..", wait:5) do
find(:xpath, ".//span[contains(text(),  '1 IndexTwistyLevel1')]/../../../span[#class='ui-tree-toggler fa fa-fw fa-caret-right']", wait:5).click
end
end
Error : Capybara::ElementNotFound: Unable to find visible xpath "//div[.//span[contains(text(),  '1 IndexTwistyLevel1')]]/span[#class='ui-tree-toggler fa fa-fw fa-caret-right']"
Your code has a number of issues, which indicate it can't actually be working like you claim. If you fix the code and provide the HTML fragment it should be matching against we can narrow done to the issue, but for now the errors are:
Firstly, you have mismatched/non-escaped
's and )s in your XPath expressions (can't have inside a string surrounded bys so it's obvious you haven't copy/pasted your actual code)
Secondly, ::after is not valid XPath - ::after pseudo elements are purely CSS and can't be accessed from XPath, so including that in your selector isn't going to give the expected results. This should result in an invalid selector error being raised by Chrome.
Thirdly, by not starting your selectors with . you're completely defeating the within scoping block - see https://github.com/teamcapybara/capybara#beware-the-xpath--trap
Finally, using visible: false on an element you want to click makes no sense, since you can't click on an element that isn't displayed on the page.
Unfortunately its tough to tell which of these may be causing your actual issue (if any) since the code you have provided isn't valid.
within(:xpath, config['documents_obj']['FRChildTreeXpath'].sub('TEXT', parent), wait:5) do
elem = find(:xpath, config['documents_obj']['childTwistyXpath'].sub('TEXT', child), visible:false, wait:5).native
page.driver.browser.action.click(elem).perform
To avoid the error which iwas gettign what i simply did, is I used capybara action builder,
Take the native element then perform the action.
It worked perfectly in my case.
Reference : https://seleniumhq.github.io/selenium/docs/api/rb/Selenium/WebDriver/ActionBuilder.html

Unable to enter a value in field using Xpath

I am unable to enter a value in field which is having type as "text" after running the automated script. Please find details below
Field Name: "Spot/Content Name
Xpath value for the above field :
.//*[#id='154']/div[3]/div[1]/div/div/div/div[1]/div/div/div[2]/div/div[2]/input
Automated Script for the above Xpath:
driver.findElement(By.xpath(".//*[#id='154']/div[3]/div[1]/div/div/div/div[1]/div/div/div[2]/div/div[2]/input")).clear();
driver.findElement(By.xpath(".//*[#id='154']/div[3]/div[1]/div/div/div/div[1]/div/div/div[2]/div/div[2]/input")).sendKeys("Rose");
Error Message :
NoSuchElementException: Unable to locate element:
{"method":"xpath","selector":".//*[#id='154']/div[3]/div[1]/div/div/div/div[1]/div/div/div[2]/div/div[2]/input"}
I tried even the html which was shown on the xpath but it was not working.
This is not the way Xpath should be used, please go through the following link: so that you could understand it in a better way.
http://www.toolsqa.com/selenium-webdriver/choosing-effective-xpath/
Also it is always good practice to share you HTML code so that ppl could identify the problem.
Meanwhile your element can be found using CSSSelector also try this--
driver.findelement(by.cssSelector("input[id='154']")).clear();
driver.findelement(by.cssSelector("input[id='154']")).sendKeys("Rose");
Please let me know if this works..!!

Selenium webElement.clear() doesn't work with phantomJS but yes with Firefox

I am trying to use PhantomJS as a browser to make a selenium test, but I have a problem with an input.
This input is a calendar (is not type date, is text but modified by JavaScript).
First of all, I have this using FirefoxDriver and works perfectly:
webElement.Clear();
webElement.SendKeys(date);
but, using PhantomJSDriver jumps an exception which says this:
{"errorMessage":"Element must be user-editable in order to clear it.","request":{"headers":{"Accept":"application/json, image/png","Connection":"Close","Content-Length":"0","Content-Type":"application/json;charset=utf-8","Host":"localhost:53291"},"httpVersion":"1.1","method":"POST","post":"","url":"/clear","urlParsed":{"anchor":"","query":"","file":"clear","directory":"/","path":"/clear","relative":"/clear","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/clear","queryKey":{},"chunks":["clear"]},"urlOriginal":"/session/a1e4cdb0-b901-11e4-befc-c3b28b46e8f3/element/%3Awdc%3A1424437741971/clear"}}
is very extraneous because in Firefox works perfectly,
what can I do to send the data?
Also I tried to sen this data without clear it, but the default value is 20/02/2015 and when i send something just add after the current text: 20/02/201530/03/2015 and doesn't work.
attribute .text doesn't has setter, the same for getAttribute().
thanks for all,
Ivan.
#edit1: html
<input type="text" aria-haspopup="true" title="" value="20/02/2015" name="id0" id="id0" class="bg datetime hasDatepicker">
Finally i found how to do this, probably is not the best way, but in my case works.
I send the data by JavaScript with javascriptExecutor
((IJavaScriptExecutor)_driver).ExecuteScript("document.getElementById('id0').value='" + date+ "'");

Finding text on page with Selenium 2

How can I check whether a given text string is present on the current page using Selenium?
The code is this:
def elem = driver.findElement(By.xpath("//*[contains(.,'search_text')]"));
if (elem == null) println("The text is not found on the page!");
If your searching the whole page for some text , then providing an xpath or selector to find an element is not necessary. The following code might help..
Assert.assertEquals(driver.getPageSource().contains("text_to_search"), true);
For some reason, certain elements don't seem to respond to the "generic" search listed in the other answer. At least not in Selenium2library under Robot Framework which is where I needed this incantation to find the particular element:
xpath=//script[contains(#src, 'super-sekret-url.example.com')]
A simpler (but probably less efficient) alternative to XPaths is to just get all the visible text in the page body like so:
def pageText = browser.findElement(By.tagName("body")).getText();
Then if you're using JUnit or something, you can use an assertion to check that the string you are searching for is contained in it.
assertThat("Text not found on page", pageText, containsString(searchText));
Using an XPath is perhaps more efficient, but this way is simpler to understand for those unfamiliar with it. Also, an AssertionError generated by assertThat will include the text that does exist on the page, which may be desirable for debugging as anybody looking at the logs can clearly see what text is on the page if what we are looking for isn't.