Selenium using findElements - selenium

How can I automate to click the links enumerated by an item list.
*A
*B
*C
*D
*E
xpath of "*A" is html/body/ul/li[1]/a
xpath of "*B" is html/body/ul/li[2]/a
...
Is it possible to click all the items using findElements(By.xpath)?

You can use here findElement method here you can use option to find element it will be more helpful for you. If you want example code than i can provide you feel free to ask me

First answer is yes but! in case that after click you will be not redirected to other page.
you need to create collection that will contain all the li.
IList&ltIWebElement&gt liCollection = driver.FindElement(By.Xpath("html/body/ul")).FindElements(By.TagName("li");
you need to loop them one by one and invoke the click
for(int i = 0 ; i < liCollection.Count ; i++)
{
liCollection[i].FindElement(By.TagName("a")).Click;
//Thread.Sleep(2000);
liCollection = driver.FindElement(By.Xpath("html/body/ul")).FindElements(By.TagName("li"));
}
!!!STACKOVERFLOW CODE FORMAT PROBLEM!!!

try this may help you
//count the list
List<WebElement> ButtonNamelist=driver.FindElements(By.Xpath("html/body/ul"));
int listcount=ButtonNamelist.size();
for(int i=1;i<=listcount;i++){
driver.findElement(By.xpath("html/body/ul/li["+i+"]/a")).click();
//you need to navigate back here to click on the other elements use waits to load the element and click again
}

Related

How to click child links of each menu in Selenium with Java

I am trying to use the link https://www.bloomingdales.com/
Click child links of each menu .Below is the code i tried .
public void iClickOnFOBSShouldVerifyTheRespectivePages() throws Throwable {
List allElements = Elements.findElements(By.xpath("//ul[#id='mainNav']/li/a"));
for (int i = 0; i <= allElements.size(); i++) {
List<WebElement> links = Elements.findElements(By.xpath("//ul[#id='mainNav']/li/a"));
WebElement ele = links.get(i);
ele.click();
List<WebElement> childlinks = Elements.findElements("left_facet.left_nav");
for (int j = 0; j <= childlinks.size(); j++) {
List<WebElement> ele2 = Elements.findElements(By.xpath("left_facet.left_nav"));
WebElement ele3 = links.get(i);
ele3.click();
Navigate.browserBack();
}
}
Below is the error i am getting
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
Try This::List<WebElement>ele = driver.findElements(By.xpath("//ul[#id='mainNav']/li/a"));
Actions act =new Actions(driver);
Thread.sleep(4000);
for (int i = 0; i <= ele.size(); i++) {
WebElement a =ele.get(i);
act.moveToElement(a).build().perform();
Thread.sleep(2000);
List<WebElement>ChildMenu=driver.findElements(By.xpath("//nav[#id='nav']/div[2]/div/div/div[#class='flyoutCol']/div/ul/li"));
System.out.println("Sub-Menu="+ChildMenu.size());
for(int j=0;j<ChildMenu.size();j++){
ChildMenu.get(i).click();
Thread.sleep(2000);
driver.navigate().back();
Thread.sleep(2000);
act.moveToElement(a).build().perform();
On clicking any of the links, the browser will open a new page. At that moment the elements in the page corresponding to allElements, ele and ele2 disappear ("element is not attached to the page document") in the browser and are thus not valid anymore. I would expect that the first click on a submenu child would work but anything after that will fail.
What you could do is first check how many children each submenu has, store this in an array and then create a double loop somewhat similar to what you have already done. For each submenu and submenu child click, you can't use any of the webelements in memory of your program because their state was changed so you would need to initialize a completely new webelement.
With xpath you should be able to reference directly to an element like 'parent - 3rd submenu - 7th submenu child'.
I am unfortunately not able to quickly create working code, otherwise I would have done so.
What I am wondering is: what is the purpose of this code? You don't do any assertions, so if any submenu child click leads to an error page, your code will not fail. Is this desired? It might not even fail if clicking doesn't even open an error page. I guess this code would fail if some of the submenu children are present in the HTML but for some reason not visible.
If this is meant to be a test, I would recommend to make a handful of separate tests that cover a few examples (and assert that clicking leads to the expected page) instead of looping through everything. This will make the tests far more understandable for yourself and others.

how to print all sugession came in auto suggetions?

i Just started with selenium so i want to know how to handle below thing ...
when type some thing on google it gives us suggestions i want print them on console .
i have tried this
driver.findElement(By.id("lst-ib")).sendKeys("cognizant i");
List<WebElement> lst=driver.findElements(By.tagName("li"));
int ii = lst.size();
System.out.println(lst.get(3).getText());
System.out.println(lst);
for(int i=0;i<lst.size();i++){
System.out.println("hi" + lst.get(i).getText());
}
But not printing any thing on console. plz Guide me where i went wrong .
Following code waits for the suggestions to appear after you have entered some value in google search bar and then prints them one by one in console:
driver.findElement(By.name("q")).sendKeys("Cognizant i");
List <WebElement> allItems = driver.findElements(By.xpath("//*[#id='sbtc']/div[2]/div[2]/div[1]/div/ul//li/div[contains(#id,'sbse')]"));
while(allItems.size() <1)
{}
System.out.println("Total no of elements :" + allItems.size() );
for(int i=0; i< allItems.size() ;i++){
value1= allItems.get(i).getText();
System.out.println(value1);
}
Your code actually runs, and does output the suggestions - however you are grabbing all 'li' elements on the page which results in a large number of empty or irrelevant elements being present in your List lst.
You can see this if you open the Console in your browser on the google home page and search for li tags which is effectively what your code is doing.
Make your code more specific to the list items you want to collect - which reside inside a tag with the role "listbox".
The following will output the suggestions to the console:
driver.findElement(By.id("lst-ib")).sendKeys("cognizant i");
WebElement suggestionList = driver.findElement(By.cssSelector("[role ='listbox']"));
List<WebElement> suggestions = suggestionList.findElements(By.tagName("li"));
for(WebElement suggestion : suggestions){
System.out.println(suggestion.getText());
}

How to handle duplicate object in selenium?

I want to send values for particular field
I have found Password locaters value is same on this website.
How to handle same objects which have same id,name,tagname etc.?
You can find them like that :
First one :
driver.findElement(By.xpath("//form[#id='loginForm']/div/div/input[#id='password']")
Second one :
driver.findElement(By.xpath("//form[#id='registration-form']/div/div/input[#id='password']")
With that solution, you'll be sure to find the right element even if an other id=password is added before the one you are looking for.
You can use List<WebElement> to create a list of elements with "same id,name,tagname" and perform indexed operations as :
List <WebElement> elements = driver.<your locator strategy>;
for (int i = 0; i< elements.size(); i++) {
elements.get(0).<perform your action>;
}

How to click webelement that contains text i searched for using selenium webdriver?

I'm searching for some text using the foloowing code and trying to click on it, but for some reason i cant figure out no action takes place...why is that?
code:
for (int i=0; i<AllTableTd.size();i++){
if (AllTableTd.get(i).getText().toLowerCase().contains("autesting".toLowerCase())) {
AllTableTd.get(i).sendKeys(Keys.RETURN);
break;
}
If you want to use that web element do
WebElement we = driver.find element(your element);
we.click()
Or
driver.find element(your element).click();

Selenium Xpath Not Matching Items

I am trying to use Selenium's Xpath ability to be able to find an set of elements. I have used FirePath on FireFox to create and test the Xpath that I have come up with and that is working just fine but when I use the Xpath in my c# test with Selenium nothing is returned.
var MiElements = this._driver.FindElements(By.XPath("//div[#class='context-menu-item' and descendant::div[text()='Action Selected Jobs']]"));
and the Html looks like this:-
Can Anyone please point me right as everything that I have read the web says to me that this Xpath is correct.
Thanking you all in-advance.
Please post the actual HTML, so we can simply "drop it in" into a HTML file and try it ourselves but I noticed that there is a trailing space at the end of the class name:
<div title="Actions Selected Jobs." class="context-menu-item " .....
So force XPath to strip the trailing spaces first:
var MiElements = this._driver.FindElements(By.XPath("//div[normalize-space(#class)='context-menu-item' and descendant::div[text()='Action Selected Jobs']]"));
Perhaps you don't take into consideration the time that the elements need to load and you look for them when they aren't yet "searchable". UPDATE I skipped examples regarding this issue. See Slanec's comment.
Anyway, Selenium recommends to avoid searching by xpath whenever it is possible, because of being slower and more "fragile".
You could find your element like this:
//see the method code below
WebElement div = findDivByTitle("Action Selected Jobs");
//example of searching for one (first found) element
if (div != null) {
WebElement myElement = div.findElement(By.className("context-menu-item"));
}
......
//example of searching for all the elements
if (div != null) {
WebElement myElement = div.findElements(By.className("context-menu-item-inner"));
}
//try to wrap the code above in convenient method/s with expressive names
//and separate it from test code
......
WebElement findDivByTitle(final String divTitle) {
List<WebElement> foundDivs = this._driver.findElements(By.tagName("div"));
for (WebElement div : foundDivs) {
if (element.getAttribute("title").equals(divTitle)) {
return element;
}
}
return null;
}
This is approximate code (based on your explanation), you should adapt it better to your purposes. Again, remember to take the load time into account and to separate your utility code from the test code.
Hope it helps.