Clicking on <li> list item not using Selenium Java - java

The following list represents page navigation buttons:
<div class="list">
<ul class="pageNav">
<li class="paginate_button ">
1</li>
<li class="paginate_button ">
2</li>
<li class="paginate_button ">
3</li>
</ul>
</div>
To go to the second page for instance, I am using this Selenium Java code:
//after setting up webdriver
List<WebElement> li = driver.findElements(By.className("pageNav"));
System.out.println(li.get(2).getText());
li.get(2).click();
It's printing the text correctly "2", but not clicking or navigating correctly as if I was manually doing it on the actual website. I also tried replacing the link with an actual link like:
Visit our page
But still no luck. What am I doing wrong?
Thank you in advanced!

Try any of these below code.
In your tried code, I have noticed that you were using class locator to click on links element. But your <ul> tag does not contains the link. Inside <ul> tag, <li> tag is present and each <li> tag contains separate <a> tag.
so, here you should go with xpath or cssSelector locator.
Method 1) By using xpath locator
List<WebElement> links = driver.findElements(By.xpath("//ul[#class='pageNav']/li/a"));
System.out.println(links.size());
links.get(1).click(); //indexing start from 0, if you want to click on second link then pass indexing as 1.
Suggestion:- Instead of using absolute xpath, use relative xpath.
Method 2) By using cssSelector locator
List<WebElement> links = driver.findElements(By.cssSelector("ul.pageNav>li>a"));
System.out.println(links.size());
links.get(1).click(); //indexing start from 0, if you want to click on second link then pass indexing as 1.

Try below code
//getting all the anchor tag elements and storing in a list
List<WebElement> links = driver.findElements(By.xpath("//ul[#class='pageNav']//li[starts-with(#class,'paginate_button')]/a"));
System.out.println(links.size());
//performs click on second links
links.get(1).click();

If you're facing any abnormal difficulty which you are not able to handle directly , then you can first try to move to that element using actions class then click it as below:
WebElement we = driver.findElement(By.cssSelector("div.list > ul.pageNav li:nth-child(2));
Actions action = new Actions(driver);
action.moveToElement(we).click().build().perform();

Related

Selenium find and click img with a text inside div

I am new to xpaths in selenium and trying to click on Next> image/button in the code below. I have tried following two xpaths but its not working and giving no element not found error.
By.xpath("//div[#class='pzbtn-mid']/img[contains(text(), \"Next >\")]"))
By.xpath("//div[#class='pzbtn-mid']/img[contains(text(), 'Next >')]"))
What am i doing wrong here?
<div class="pzbtn-mid" data-bindprops="innerHTML" data-click="...."> ==$0
<img src="webwb/zblankimage.gif" alt="" class="pzbtn-i">
"Next >"
<img alt="" src="webwb/zblankimage.gif" class="pzbtn-i">
As per the HTML you have shared to click() on the Next> image/button you can use the following xpath :
By.xpath("//div[#class='pzbtn-mid']/img[#class='pzbtn-i' and #src='webwb/zblankimage.gif']"))
Note : The text Next > is not within any of the <img> tags but within the <div> tag. Hence to click on the image/button you have to reach till the <img> tag.
You can also use xpath below,
By.xpath("//div[contains(#class,'pzbtn-mid') and contains(.,'Next >')]//img")
It clicks the first image if the img belongs to next. Othervise you should click the second img like below;
driver.findElementsBy((By.xpath("above xpath")).get(1));

Unable to locate element using Selenium Webdriver

I am having sticky nav bar which has few list elements where each contains href element. When I tried to locate element I am getting the error.
Following is my HTML code :
<div class="nav" id="sticky">
<div class="container">
<ul class="main-nav">
<li>Dashboard</li>
<li><a href="../MEFAcademicDash/StudentUI/StudentHome.aspx"
title="Academic Dashboard">Academic</a></li>
<li>Notices</li>
I want to locate Academic through Webdriver, I am getting the error like this Unable to locate the element.
org.openqa.selenium.NoSuchElementException: Unable to locate element: /html/body/div/form/div[5]/div[1]/ul/li[2]/a
As per the HTML you have shared you need to induce WebDriverWait for the element to be visible / clickable. To click() on the link with text Academic you can use the following line of code :
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#class='nav' and #id='sticky']/div[#class='container']/ul[#class='main-nav']//li/a[#title='Academic Dashboard' and contains(#href,'../MEFAcademicDash/StudentUI/StudentHome.aspx')]"))).click();
Can you try below-mentioned xpath?
//*[text() = 'Academic']
Also, use actions driver to perform click action

Clicking on Image Link with Selenium webdriver java

I have looked at the answers to similar questions and it seems like the code that I have should work but I get "Cannot click on element" error when the code invokes click on the web element.
Following is html markup segment
<div class="x-tree-node-item">
<a title="Manage Users" class="sidenavmenu_unselected" id="m-22" onclick="toggleMenu('22', '');" href="#">
<img title="" align="bottom" id="mi-22" alt="" src="ca/images/arrow.png" border="0">Manage Users
</a>
<div style="margin-left: 1em;">
<ul class="submenu-show" id="mp-22" style="height: auto; display: none;">
<li>
...
</li>
</ul>
</div>
Java code to locate the link is:
By xpath=By.xpath("//a[contains(#title,'Manage Users')]/img");
WebElement manageUsers = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(xpath));
manageUsers.click();
It finds the element but I get error:
org.openqa.selenium.ElementNotInteractableException: Cannot click on element
The ids are generated dynamically so we can't find by id and image source is used by multiple links.
Thank you for your help.
* Update *
The problem was solved with help from JeffC and Xwris. JeffC's last comment showed that there are multiple nodes being found. So, I added following code:
List<WebElement> manageUserImages=driver.findElements(xpath);
for (WebElement manageUserImage:manageUserImages) {
if (manageUserImage.isDisplayed()) {
manageUserImage.click();
}
}
Since there is only element displayed at one time with "Manage Users" as title, this finds the correct elements and delivers the desired results.
#JeffC, if you can post an answer with your comment, we can mark that answer as the correct answer.
Thanks again to everyone who helped.
It looks your xpath is wrong.
Personally I would start from the div and the drill down to the actual < a > tag.
In some cases where your web-element sits under a < li > tag, I would go even further up the tree and select a div which is not hidden.
i.e you instruct it to search for under the specific < div >
Who told you you can select only by id? You can use anything! :)
This should work.
//div[#class='x-tree-node-item']//a[#title='Manage Users']
This should work as well. Correct usage of 'contains' is as follows:
//div[#class='x-tree-node-item']//a[text()[contains(.,'Manage Users')]]
Hope this helps!
PS. notice that text contains is case-sensitive and will match partial text.
So if you searched for:
//a[text()[contains(.,'age User')]]
it will still be a successful match!
Update after OP's comments:
You don't actually need xpath helper. You just hit F12 in your browser and then CTRL+f so you open a search field at the bottom. Please see my example on how I locate the title of your question with partial text match ('Image').
Also notice next to xpath where it says 1 of 1 (meaning that our element is unique). Try to do the same for your case. I suspect that you need to go higher up the tree and start from an earlier < div > so you can locate the rest.
Leave off the "/img" part of your locator. You want to click the anchor (a) not the image itself.
By xpath=By.xpath("//a[contains(#title,'Manage Users')]");
WebElement manageUsers = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(xpath));
manageUsers.click();
Alternatively, the locator could be: //a[#id='m-22']

Opening a href link in Selenium Java

I am trying to click on the following a href link in selenium. I have tried using xpath and By.linkText() and By.cssSelectort() but I have not be able to locate the element. Any help is much appreciated
driver.findElement(By.linkText("CCC_PH3_Sandbox_Keybridge: CCC PH3 Sandbox Keybridge")).click();
and By.xpath() but its unable to locate the element
WebElement course = driver.findElementByXPath("html/body/table/tbody/tr/td/div/div[2]/table/tbody/tr/td[3]/a/span[1]");
course.click();
css locator :
driver.findElement(By.cssSelector("a[href*='/webapps/portal']")).click();
Here is the html snippet:
<img width="12" height="12" src="/images/ci/icons/bookopen_li.gif" alt="">
<a target="_top" href=" /webapps/portal/frameset.jsp?tab_tab_group_id=_2_1&url=%2Fwebapps%2Fblackboard%2Fexecute%2Flauncher%3Ftype%3DCourse%26id%3D_2135_1%26url%3D">CCC_PH3_Sandbox_Keybridge: CCC PH3 Sandbox Keybridge</a>
Try using By.partialLinkText() as below :-
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.partialLinkText("CCC_PH3_Sandbox_Keybridge"))).click();
Edited:- As you have mentioned this element is inside two iframes with id navFrame and contentFrame, you need to switch that iframes one by one before finding element as :-
driver.switchTo().frame("navFrame");
driver.switchTo().frame("contentFrame");
//Now find desire element
new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.partialLinkText("CCC_PH3_Sandbox_Keybridge"))).click();
//After doing all stuff inside iframe switch back to default content
driver.switchTo().defaultContent();

Selenium, JAVA - how to find such element?

Do you know how to find and click at an element like this:
<div class="offer ctrlOpenOfferInfo">
<a class="linkOffer" href="offer_view.html?id=1007"/>
<p class="photo">
<p class="name">New offer</p>
<p class="price">123</p>
<div class="rate ctrlViewRateOffer" data-value="0.0000">
<p class="date"/>
<div class="hide info">
<div class="bgInfo"/>
using Selenium WebDriver and using the name of the element as there are few very similiar elements on the page?
Here's what I've tired so far:
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[text()='New offer']")));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//*[#id='formDevelopmentElementAdd'][text()='New offer']")));
driver.findElement(By.xpath(".//*[#id='formDevelopmentElementAdd']/div/p[2][text()='New offer']")).click();
or:
driver.findElement(By.xpath("//p[#class='name'][text()='New offer']")).click();
or:
String address = driver.findElement(By.xpath("//*[contains(text(), 'New offer') and #class='name']")).getAttribute("href");
driver.get(baseUrl + address);
or:
driver.findElement(By.xpath("//a[Text()='New offer']")).click();
I've tried these with text, class, xpath...
Assuming you want to click the p tag containing New offer:
I would think this element is not inside an iframe. If so, you must use driver.switchTo().frame("name or xpath or css for frame locator"); first before start looking for element.
Now, how can you find that element. Consider the following options:
Using xpath text based search
//p[.='New offer']
//to be more precise you can do
//p[#classs='name'][.='New offer']
You can use By.className('name') to identify that element even though that name does not look like unique to me
Using cssSelector
.name
using nth-child() function of cssSelector
.offer.ctrlOpenOfferInfo>a>p:nth-child(2)

Categories