How to click on hidden element in Selenium WebDriver? - java

I have a grid which displays some records. When I click on a record and inspect that element it is shown that it is hidden but it is visible in the grid.
My HTML is:
<a href="http://192.168.1.6/eprint_prod_3.8/settings/othercost_add.aspx?type=edit&id=805" title="Plastic Spiral Bind"
<div style="float: left; width: 99%; overflow: hidden; height: 15px; overflow: hidden"> Plastic Spiral Bind </div>
</a>
The above code is hidden while inspecting but it is visible in grid.
Selenium code:
driver.findElement(By.partialLinkText("Plastic Spiral Bind")).click();

First store that element in object, let's say element and then write following code to click on that hidden element:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);

You have two approaches. Selenium has been specifically written to NOT allow interaction with hidden elements. The rational is that if a person cannot perform that action, then neither should Selenium. Therefore, to perform the click via Selenium, you must perform the action a user would do to make that button visible (e.g mouse over event, click another element, etc) then perform the click once visible.
However, Selenium does allow you to execute Javascript within the context of an element, so you could write Javascript to perform the click event even if it is hidden.
My preference is to always try and perform the actions to make the button visible

Here is the script in Python.
You cannot click on elements in selenium that are hidden. However, you can execute JavaScript to click on the hidden element for you.
element = driver.find_element_by_id(buttonID)
driver.execute_script("$(arguments[0]).click();", element)

overflow:hidden
does not always mean that the element is hidden or non existent in the DOM, it means that the overflowing chars that do not fit in the element are being trimmed. Basically it means that do not show scrollbar even if it should be showed, so in your case the link with text
Plastic Spiral Bind
could possibly be shown as "Plastic Spir..." or similar. So it is possible, that this linkText indeed is non existent.
So you can probably try:
driver.findElement(By.partialLinkText("Plastic ")).click();
or xpath:
//a[contains(#title, \"Plastic Spiral Bind\")]

I did it with jQuery:
page.execute_script %Q{ $('#some_id').prop('checked', true) }

If the <div> has id or name then you can use find_element_by_id or find_element_by_name
You can also try with class name, css and xpath
find_element_by_class_name
find_element_by_css_selector
find_element_by_xpath

Use an XPath of the link by using Selenium IDE to click the element:
driver.findelement(By.xpath("//a[contains(#title, \"Plastic Spiral Bind\")]")).click();

Related

Exclude non visible elements with XPath when display: none; is set in CSS class?

I need to exclude elements from XPath where display: none; is set in the CSS class. The solution suggested here will not work when the given element has a CSS class in which the display: none; is set as pointed out in this comment.
In my specific example, the element has a class named error-result with CSS set to:
.error-result {
display: none;
}
Here's the XPath I tried:
.//*[contains(text(),'XXXXXX')][not(ancestor::div[contains(#style,'display: none')])][not(descendant::div[contains(#style,'display: none')])]
The problem is, Selenium still identifies the undesired element since display: none; is set only in CSS class.
How can I exclude such elements?
I'm using Selenium WebDriver with Java.
Thanks
Xpath executed against the page source scope.
It will work only if you able to find the display property in style attribute for the element in page source text (the result value of driver.getPageSource())
Unfortunately, in many cases css styles not reflected by the page source, so you should execute additional driver commands like element.getCssValue('displayed'). (But for check visibility I suggest to use isDisplayed()).
It means, you should iterate by the elements list and get sublist by some condition, which increases driver requests amount, but it's the only way to solve this.

Selenium Web driver clicking images

How do I select in image on and click on it using Selenium web driver? Say if it says this
<style type="text/css"> <ul id="nav"> <li> <li> <li> <li> <li> My Dashboard </li> </ul>
Would I use
driver.findElement(By.linkText("My Dashboard")).click();
or something else?
If you want to click on link in your example, you can use the selector you wrote, different kinds of css selectors (for example, By.cssSelector("#nav a") (looks for a link inside the "nav" list) or By.cssSelector("a[href='dashboard.action']") (looks for a link with specific href)) or using xPath selectors.
The important thing is to have a unique identifier to locate your element and an identifier that will fire 100% of the time.
For example, if you expect the link text to change on you, then don't look for that particular link text, because you have no guarantee that it will work 100% of the time.
Similarly, if there are 30 different elements that have the same id tag, don't use that either.
If things turn out to be very complex... that is, if you are in a large page with a lot of unknown variables, find by XPATH.
In the end, it really depends on the complexity of the website you are entering, and the goal of what you need done.
For more information, go to the Selenium javadocs and click BY on the sidebar for a list of different methods and how to use them.
If you need to click a link with an image, it would be better to locate the element with the explicit wait.
Example :
new WebDriverWait(driver, timeout).until(ExpectedConditions.presenceOfElementLocated(locator));

Clicking on a button based on some text in div

How can I click on a button based on the text "See More" or "Sign Up"
<div data-reactid=".0.0.$LandingPage.0.1.0.0.1.0.3">
<button class="arda-button btn -primary" data-reactid=".0.0.$LandingPage.0.1.0.0.1.0.3.$main-menu-see-more">See More</button>
<button class="arda-button btn -primary" data-reactid=".0.0.$LandingPage.0.1.0.0.1.0.3.$main-menu-sign-up">Sign Up</button>
</div>
</div>
Or based on the html above can you see a unique way of identifying and clicking on the two buttons?
Thanks
Identify using contains text() as 'see more' and 'sign up', should work.
By.xpath("//button[contains(text(),'See More')]")
By.xpath("//button[contains(text(),'Sign Up')]")
You can use XPATH ( Consider the Xpath is not big and Ugly) where each button will be separate.
If XPATH is ugly and long use regular Expression where data-reactid CONTAINS "main-menu-see-more" for "See More" button. And data-reactid CONTAINS main-menu-sign-up for Sign up button
"//*[contains(#data-reactid,'main-menu-see-more')]"
" //*[contains(#data-reactid,'main-menu-sign-up')]"
What about linked Text "See More" and "Sign Up".
Please share your feedback its working not......
I avoid XPath like the plague unless absolutely necessary because it's complicated, slower than other methods, and more prone to breaking (in general). I would do this using a CSS Selector.
The data-reactid is unique for each of these elements so I would use those to find the desired elements instead of the text.
driver.findElement(By.cssSelector("button[data-reactid='.0.0.$LandingPage.0.1.0.0.1.0.3.$main-menu-see-more']")).click();
This code finds a button that has the specified data-reactid and clicks it.
CSS Selectors are very powerful and it lets you avoid XPath... which is a good thing. :)
CSS Selector reference

Selenium Webdriver: IE can't find radio buttons nor checkboxes for using click() on them

I am building a test suite for a basic registration page (it has a large number of text fields + some radio buttons and checkboxes here and there). I am using Selenium Webdriver solution and tests are written in Java. While the tests are running fine on Firefox and Chrome, the Internet Explorer tends to run into trouble when it comes to clicking on radio buttons or checkboxes. All the radio buttons and checkboxes have id-s defined and from what I've learned it's the most convenient way to find an element on the page, so I was quite surprised when I started getting these issues. The method for finding the radio button looks like this:
public static WebElement rad_Male(WebDriver driver) {
element = driver.findElement(By.id("male"));
return element;
}
The click is done in a following way:
rad_Male(driver).click();
As I said, Firefox and Chrome can easily click on checkboxes and radio buttons, but when running tests in IE I get a following exception (the element is visible all the time and I can click on it with mouse):
org.openqa.selenium.ElementNotVisibleException: Cannot click on element
I've also tried using an explicit wait in order to let the elements load before accessing them, but had no luck - I get TimeoutException as soon as the function times out. I suspect it has something to do with the page design, but unfortunately I have no access to the page source code, so I cannot change the page structure to make it easier to test.
The radio button is placed inside a number other divs and I think there is also a table used to align this and other elements around, but this doesn't look too complicated. Here's the code for radio button:
<input type="radio" value="M" name="sex" id="male" tabindex="110">
I think I saw some javascript click suggestion in one of the similar topics, but before resorting to this I wanted to make sure that there is no other way to make it work using the means that Webdriver provides.
I've just started learning Selenium and I try to get my work done on the go while learning new stuff all the time, so I am not too experienced with this yet.
If you would like some more details, please ask as I am not sure if I've got all included.
Thanks in advance!
Hi again and thanks to everyone who responded! A friend of mine had a look at this issue and managed to figure out what was causing this. The radio button was actually contained inside another div in a following way:
<div class="radio" id="uniform-male">
<span>
<input type="radio" value="M" name="sex" id="male" tabindex="110">
</span>
</div>
It appears that this parent div "uniform-male" kind of concealed this button, because Selenium was able to click on this div and as a result, the radio button underneath it was clicked.
I guess I should have posted the code for the radio button along with some code of it's parent elements in the first hand, so it would have been easier to debug it.
Once again I appreciate all the help I received from you on this question, thanks!
try using this before you click on the element, maybe IE is a bit slower:
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(anId)));
As per the error you are getting, I think selenium is trying to click on the element, i.e., radio button, which is probably not visible yet.
To resolve this, try adding an explicit wait in the method rad_Male like this (Assuming 'element' is a reference of 'WebElement class'):
public static WebElement rad_Male(WebDriver driver) {
//waiting 30 seconds for the element to be visible
element = new WebDriverWait(driver, 30).until(ExpectedConditions.visibilityOfElementLocated(By.id("male")));
return element;
}
Then, use it to click the button like this:
element = rad_Male(driver); //Fetching the value returned by rad_Male method
if(element!= null)
element.click();
else
System.out.println("Element is not visible");

Selenium: Dynamic buttons and classes?

So, I was trying out a test case on a website and Selenium registers the events perfectly. Now, if I have to search for a particular class and get the innerHTML of that class, how would I do it assuming that I am using Java as the driving language?
Just to be more clear. I have a class like this:
<h1 class="classname">.....</h1>
I want to get the entire text between those tags.
And finally, if the ids of the buttons on the page are dynamically generated, how would I test the clicking action on them? These button, I presume are using ajax. When I click on the button, Selenium generates this:
//div[#id='c4aef94de622f51859827294']/div/div/div[1]/span[2]/span/span[3]/a
and the actual HTML of the button is this:
<a href="#" bindpoint="forward" class="ButtonForward"/>
Is it even possible to click on the button?
You could use the getHtmlSource command to get the entire HTML source, and then use something else to parse the HTML in Java and extract the contents of the target element.
You can locate elements without using an ID, for example if this is the only such button on the page you could locate it:
Using CSS locators:
selenium.click("css=a.ButtonForward");
Using XPath locators:
selenium.click("xpath=/descendant::a[#class='ButtonForward']");

Categories