Selenium webdriver: How can I click these links? - java

<a onclick="requestReportGeneration('857f23e1baa767622a91f970963d8918', 'reportDiv31','CSV')" href="javascript:void[0];">CSV</a>
<a onclick="requestReportGeneration('64107e36323e5877c986edc98a17b6e8', 'reportDiv32','CSV')" href="javascript:void[0];">CSV</a>
<a onclick="requestReportGeneration('2cad4d4e5c8855c47a88b6ddf8345735', 'reportDiv33','CSV')" href="javascript:void[0];">CSV</a>
I have these three links on a page and I want to click each one in turn. I am reading all the links on the page into a list of WebElements and then I go through each one in turn if the href contains javascript:void[0] I then try to click it:
for (int i = 0; i < allLinks.size(); i++) {
String reportLink = allLinks.get(i).getAttribute("href");
if (reportLink.contains("javascript:void[0];"))
{
allLinks.get(i).click();
/// Do some more stuff
}
The problem is I keep getting an error saying the element is not visible. I have also tried just loading the page and instead of getting all the links doing
driver.findElement(By.xpath("//a[contains(#href,\"javascript:void[0]\")]")).click();
but that also just gives element not visible error.
Can anybody tell me why this isn't working?

Try putting a breakpoint before the while loop, debug your script, then step into it and use Eclipse's Display tab to interrogate what is up with the links. Try evaluating sample statements like:
allLinks.size();
allLinks.get(i).isDisplayed();
allLinks.get(i).isEnabled();
There must be something odd about the links (or the way webdriver is seeing them), but debugging like this will let you find out what it is.

Related

Selenium Automation unable to click the link

I am trying to automate some task for a website. In on page there is a option to "Move to next page" its not usual a link but when I click it takes me to the next page. The code is given below. I tried all possible ways to locate it by id, classname, xpath and css selector none of them are working. Please help me to find the way for cases with javascript:void(0). I tried the methods from some other stackoverflow questions asked by others...those are also not working.
WebElement skip = driver.findElements(By.cssSelector("a[href*='javascript:void[0]']"));
skip.click();
You can find the <a> and use filter on the text "Move to next page" to locate the element you're after, unless you have multiple elements with that text.
Also check if the id is unique, if there are more than one element with that id, it returns the first hit. You can use jQuery regex match to find them all, and find a way to locate that element.
EDIT: with the source code you provided:
::before "Move to next page" == $0
Ignore those $0 & ::before that are obviously copied from the developer console of the browser, it should be something like this:
Move to next page
So, in Selenium, you can locate it with:
String jsScript = "return $('a.someclassname:visible').filter(function () { return $(this).text() == 'Move to next page'; });";
Object object = ((JavascriptExecutor)this.driver).executeScript(jsScript, new Object[0]);
if (WebElement.class.isInstance(object))
{
return (WebElement) object;
}
if (List.class.isInstance(object))
{
return (WebElement) ((List)object).stream().filter(WebElement.class::isInstance).findFirst().orElse(null);
}
return null;
Either of these methods should work
WebElement element = driver.findElement(By.linkText("Move to next page"));
element.isEnabled();
element.click();
WebElement element = driver.findElement(By.partialLinkText("Move to next page"));
element.isEnabled();
element.click();
Use below xpath to click on-
driver.findElement(By.xpath("//a[#class='someclassname'][contains(text(),'Move to next page')]")).click();

Selenium how to click on this kind of link

I'm having trouble with this particular link because is dynamic, it doesn't have an specefic name or id, but i know that all those links are inside a span with has a class. I try to get a list of WebElements to get all the spans with the class "more" to get the bunch of links inside but i get this error:
org.openqa.selenium.WebDriverException: Element is not clickable at point (96, 21). Other element would receive the click: <div class="priceFinderHeaderLogoWrap"></div>
this how the html code looks likes:
<span class="more">
<a onclick="setPID(27272);ta.fireEvent('hotels_lists_engagement_tracking.fired', {type: 'ReviewCount', element: this});ta.setEvtCookie('Reviews', 'ReviewCount', '1461750', 1, '/Hotel_Review');" target="_blank" href="/Hotel_Review-g150800-d1461750-Reviews-City_Express_Plus_Reforma_El_Angel-Mexico_City_Central_Mexico_and_Gulf_Coast.html#REVIEWS">254 opiniones</a></span>
my java code:
List<WebElement> links = driver.findElements(By.className("more"));
System.out.println(links.isEmpty());
for (int i = 0; i < links.size(); i++) {
links.get(i).click();
// do something in the web page...
}
Try this
List<WebElement> links = driver.findElements(By.XPath("//span[#class='more']/a"));
As per provided information, links are dynamic which is inside span with class as more. So in the code you tried
List<WebElement> links = driver.findElements(By.className("more"));
asking to load all span webelements but actually you need links right?
So if you need to load all links in particular span with class more then try like below
List<WebElement> links = driver.findElements(By.xpath("//span[#class='more']/a"));
provided that page contains unique span which you trying to get links.Then go for 'for' loop and click on link.
if you still get same issue, then use Actions to click on element. for example like below
for(int i=0; i<links.size(); i++){
new Actions(driver).moveToElement(links.get(i)).click().build().perform();
}
if your intention is to click on span as per code you tried then try Actions as above to get out of the exception.
Please make a note that there is chance of getting stealelement exception as you are performing click which may leads to page loads and driver loose its references to collected webelements in for loop.
Thank You,
Murali

can't click on checkbox to uncheck it seem like it's hidden

the checkbox is checked be default and can't click on it to uncheck. here is my code but it came back as error saying element is not currently visible and so may not be interacted with. org.openqa.selenium.ElementNotVisibleException.
String checkboxXPath =("//input[contains(#type='checkbox',#name='key_IT_CONFIG.ios.restriction.functionality.enable.camera_checkboxVal')]");
WebElement elementToClick = driver.findElement(By.xpath(checkboxXPath));
elementToClick.click();
Website code
<input type="checkbox" class="uwp_inputCheckBox"
name="key_IT_CONFIG.ios.restriction.functionality.enable.camera_checkboxVal"
id="key_IT_CONFIG.ios.restriction.functionality.enable.camera"
value="true" dir="ltr" hierarchy="false" expand="true"
checkedval="true" uncheckedval="false"
onclick="checkboxChange('IT_CONFIG.ios.restriction.functionality.enable.camera')"
checked="checked">
whole code
whole code http://imageshack.com/a/img661/1720/SIi6Xj.png
I think you should use explicit wait until element get visible. Please check update code here and use it:
String checkboxXPath =("//input[contains(#type='checkbox',#name='key_IT_CONFIG.ios.restriction.functionality.enable.camera_checkboxVal')]");
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(checkboxXPath)));
WebElement elementToClick = driver.findElement(By.xpath(checkboxXPath));
elementToClick.click();
I have a couple suggestions. I'm not sure why your XPath is so complex when you have an ID on the element you want to click. Try this...
driver.findElement(By.id("key_IT_CONFIG.ios.restriction.functionality.enable.camera"));
I'm kinda guessing that won't work. Looking at the HTML, I see the SPAN right above the element that you want to click and it has an onclick on it. I'm guessing that if you click that, it might trigger the click of the checkbox... so let's try that...
driver.findElement(By.cssSelector("span.uwp_checkBoxSpan.uwp_checkBoxChecked"));
You might need to check my spelling on the class names... I couldn't copy/paste since it's a picture.
Since Selenium works on Javascript I would suggest you to test the checkbox clicking thing manually by entering a Javvascript. Here are the step you need to follow:
Execute the test case manually up till where your script failed.
Goto browsers developer tools option->Console. Enter a javascript
command document.getElementById('key_IT_CONFIG.ios.restriction.functionality.enable.camera').click()
If this works then there is no reason why your code shouldn't work.

How best should I interact with a this <li> from Selenium Java Webdriver

I am trying to interact with the Nike shoe online shop, login and then select a shoe size from the list and then press add to cart button from Selenium's Java WebDriver:
http://store.nike.com/us/en_us/pd/air-max-2014-running-shoe/pid-830258/pgid-774364
First of all I cannot seem to find the correct <li> element and select it - and need some advise on how to do it.
I am finding my code does not work for selecting a shoe size : pastebin.com/6K1RpPKL (as guided by the kind user on the first response.
The element type in li is not select. Use following code instead, it will work fine.
WebElement shoeSizes = driver.findElement(By.xpath("//div[contains(#class,'exp-pdp-size-container')]/a"));
shoeSizes.click(); // Expanded
String shoeSize = "8.5";
WebElement shoeSizeSel = driver.findElement(By.xpath("//li[text()='"+shoeSize+"']"));
shoeSizeSel.click(); // Size selected
driver.findElement(By.xpath("//div[#class='exp-pdp-save-container']/button")).click(); // Added to cart
As far as advice goes, you should first learn the basics like identifying elements, using locators before asking these kind of question. Go through these: Selenium Docs, Mozilla Blogs. Many such resources are available on web.
First off, you should get away from the IDE if you are wanting more robust test-writing like flash. For your login issue, this is simple.
Using the getting started with selenium framework your test would look like:
#Config(url="http://store.nike.com/us/en_us/pd/air-max-2014-running-shoe/pid-830258/pgid-774364")
public class NikeTest extends AutomationTest {
#Test
public void testNike() {
click (By.cssSelector("div.login.nav-section > a"))
.setText(By.cssSelector("form[name='login-form] input[name='email']"), "<My Username>")
.setText(By.cssSelector("form[name='login-form] input[name='password']"), "<My Password>")
.click (By.cssSelector("form[name='login-form] button.exp-login-submit")
// now we're logged in.
// let's select a size of shoe.
.click (By.cssSelector("div.exp-pdp-size-and-quantity-container > a.exp-pdp-size-dropdown") // now it's expanded.
.selectOptionByText(By.cssSelector("select[name='skuAndSize']"), "10.5") // you can replace 10.5 with whatever option you need.
}
}
Those are some CSS selectors you can use. Also per your Flash thing, i think you're out of luck buddy.. I hadn't heard of any very successful solution with automating flash.
One key thing here:
Make sure you know what element is receiving the click. Selenium IDE doesn't do a great job determining WHAT exact element is receiving the click. My guess is that it was trying either the <div> or <li> when it's the <a> that actually makes the dropdown come down.

Clicking on Google Result Suggestions

Just for learning purpose, I am trying to click on the third element of the Google Results Suggestions
In the above picture, i want to click on qubool hai. My code gets the result suggestions and clicks the 3rd element.
List<WebElement> resultsuggestion = driver.findElements(By.cssSelector(".gssb_m > tbody:nth-child(1) > tr"));
new Actions(driver).click(resultsuggestion.get(2));
But Selenium doesn't click on it. Kindly let me know if anything wrong in the above code or suggest me alternative solutions
Try changing your code to:
WebElement result = driver.findElement(By.cssSelector(".gssb_m > tbody > tr:nth-child(3)"));
result.click();
using the :nth-child typically is necessary for specifically identifying children. You seem to be trying to find multiples of only 1 tbody.
furthermore, using the Actions class for a simple click is very unnecessary when you have the WebElement#click method.
Following is another way I found:
WebElement result = driver.findElement(By.cssSelector(".gssb_m tr:nth-of-type(3)"));
result.click();
.gssb_m tr:nth-of-type(3) : Under class='gssb_m' element, it looks for third tr tag.

Categories