select randomly from dropdown list? - java

My html sample code is,
<div class="list">
<div class="dropdown">
<ul role="menu">
<li class="rsbListItem">one</li>
<li class="rsbListItem">two</li>
<li class="rsbListItem">three</li>
<li class="rsbListItem">four</li>
<li class="rsbListItem">five</li>
<li class="rsbListItem">six</li>
<li class="rsbListItem">seven</li>
<li class="rsbListItem">eight</li>
</ul>
</div>
</div>
How can i write Selenium scripts for this, and each time when i run it should select randomly.
I have tried to pick random elements,but it's selecting the same element each time. Here is my code.
List<WebElement> options = driver.findElements(By.xpath("//*[#role='menu']"));
Random rand = new Random();
int list= rand.nextInt(options.size());
options.get(list).click();

Selenium is not my thing but
List<WebElement> options = driver.findElements(By.xpath("//*[#role='menu']"));
This will return a list of WebElement match your request. So you should get the element (should be only one I guess) to work with it. You could also use findElement I guess.
Then, you will need to get every Option in the select you have.
List<WebElement> selects = driver.findElements(By.xpath("//*[#role='menu']"));
Random rand = new Random();
for(WebElement select : selects){
List<WebElement> options = // get every option in it
int list = rand.nextInt(options.size());
options.get(list).click();
}

// Locate the dropdown menu
WebElement drpdown = driver.findElements(By.id("id of the dropdown menu"));
// click the dropdown menu
drpdown.click();
//Get the list of dropdown options
List<WebElement> itemsInDropdown = driver.findElements(By.id("id of the dropdown list"));
// Get the size of dropdown list
int size = itemsInDropdown.size();
// Generate the random number
int randomNumber = ThreadLocalRandom.current().nextInt(0, size);
// Clicking on random value
itemsInDropdown.get(randomNumber).click();

Related

How to identify the text within the <a> using Selenium and Java

This is the code of the demo store I want to test:
<li class="level0 nav-2 parent">
<a href="http://demo-store.seleniumacademy.com/men.html"
class="level0 has-children">Men</a>
<ul class="level0">
<li class="level1 view-all">
<a class="level1" href="http://demo-
store.seleniumacademy.com/men.html">View All
Men</a>
</li>
<li class="level1 nav-2-1 first"><a></a></li>
<li class="level1 nav-2-2"><a href="http://demo-
store.seleniumacademy.com/men/shirts.html"
class="level1">text to get</a>
</li>
<li class="level1 nav-2-3"><a></a></li>
</ul>
</li>
I want to get text of those subcategories so I can later click on specific category by using text inside of a link element. My code is:
public Subcategory openSubcategory (String subcategoryName){
List<WebElement> subcategories = driver.findElements(By.cssSelector("a.level1"));
for (WebElement element: subcategories) {
if (element.getText().equals(subcategoryName)){
element.click();
break;
}
}
return new Subcategory(driver);
}
But it won't go inside loop, probably because element.getText() is empty.
To click on the WebElement with text as Shirts first you have to Mouse Hover the element with text as Men inducing WebDriverWait for the visibilityOfElementLocated and you can use the following locator strategies:
public Subcategory openSubcategory (String subcategoryName){
WebElement menuMen = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[contains(#class,'has-children') and text()='Men']")));
new Actions(driver).moveToElement(menuMen).build().perform();
List<WebElement> subcategories = driver.findElements(By.xpath("//a[contains(#class,'has-children') and text()='Men']//following::ul[1]//li/a"));
for (WebElement element: subcategories) {
if (element.getText().equals(subcategoryName)){
element.click();
break;
}
}
return new Subcategory(driver);
}
element.getText() can be empty.
Try:
element.getAttribute("value");
// or
element.getAttribute("innerHTML");
Change your CSS to be:
"a[class*='level']";
// or
"a[]";
Debug the code and check if the element is not null

How to get the text attribute of a input element? - webdriver

<ul class="list-group opened-list d-none" xpath="1">
<li class="list-group-item col-12" xpath="1">My team</li>
<li class="list-group-item col-12" xpath="1">My name</li>
<li class="list-group-item col-12" xpath="1">My film</li>
<li class="list-group-item col-12" xpath="1">My football teammate</li>
</ul>
Dropdown list without select tag
To get all li elements use .list-group.opened-list .list-group-item css selector.
Code below wait visibility of li elements and then print text for each:
WebDriverWait wait = new WebDriverWait(driver, 10);
List<WebElement> options = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector(".list-group.opened-list .list-group-item")));
options.forEach(element -> System.out.println(element.getText()));
If you want to select one of the element by text, check example here.

Unable to perform drag and drop action on an element using Selenium

I am trying to perform drag and drop action on element but its not happening.
This is the snippet of the page I am working on. Here I am trying to drag and place the Tile "Time" in position of the Tile "Approvals".
Screenshot
This is the code I am using.
Code
String sSource = "//*[#id=\"PTNUI_LAND_REC14$1_row_0"]";
String sTarget = "//*[#id=\"PTNUI_LAND_REC14$1_row_1"]";
WebElement wSource = TestBase.wDriver.findElement(By.xpath(sSource));
WebElement wTarget = TestBase.wDriver.findElement(By.xpath(sTarget));
Actions aActions = new Actions(TestBase.wDriver);
Action aDragAndDrop = aActions.clickAndHold(wSource).moveToElement(wTarget).release(wTarget).build();
aDragAndDrop.perform();
HTML
Source Element
<div class="ps_grid-row nuitile rsz_w1 rsz_h1" id="PTNUI_LAND_REC14$1_row_0" tx="1.0577777777777777" ty="1" gx=".1.0577777777777777." gy=".1.">
<div class="ps_grid-cell">
<div id="win0divPTNUI_LAND_REC_GROUPLET$13" class="ps_box-group psc_layout nuilp " tabindex="0" draggable="true" aria-dropeffect="move" aria-grabbed="false" droppable="true">
<h2 class="ps_groupleth"><span class="ps-label" id="PTNUI_LAND_REC_GROUPLET_LBL$13">Approvals</span></h2>
Target Element
<div class="ps_grid-row nuitile rsz_w1 rsz_h1" id="PTNUI_LAND_REC14$1_row_1" tx="2.057777777777778" ty="1" gx=".2.057777777777778." gy=".1.">
<div class="ps_grid-cell">
<div id="win0divPTNUI_LAND_REC_GROUPLET$14" class="ps_box-group psc_layout nuilp " tabindex="0" draggable="true" aria-dropeffect="move" aria-grabbed="false" droppable="true">
<div id="win0groupletPTNUI_LAND_REC_GROUPLET$14" class="ps_box-grouplet"><img id="PT_PORTAL_CLEAR_DOT$14" class="ps_process" src="/cs/p91h25r2x/cache/PT_PORTAL_CLEAR_DOT_1.gif" alt=""></div>
<h2 class="ps_groupleth"><span class="ps-label" id="PTNUI_LAND_REC_GROUPLET_LBL$14">Time</span></h2></div></div>
Please let me know if you require any more details.
May be you have to target on draggable elements as given below.
String sSource = "//*[#id=\"win0divPTNUI_LAND_REC_GROUPLET$13"]";
String sTarget = "//*[#id=\"win0divPTNUI_LAND_REC_GROUPLET$14"]";
WebElement wSource = TestBase.wDriver.findElement(By.xpath(sSource));
WebElement wTarget = TestBase.wDriver.findElement(By.xpath(sTarget));
Actions aActions = new Actions(TestBase.wDriver);
aActions.dragAndDrop(wSource, wTarget).build().perform();
To Drag and Drop the Tile Approvals in position of the Tile Time you can use the following code block :
WebElement from = TestBase.wDriver.findElement(By.xpath("//div[#class='ps_box-group psc_layout nuilp ' and contains(id,'win0divPTNUI_LAND_REC_GROUPLET$13')]"));
WebElement to = TestBase.wDriver.findElement(By.xpath("//div[#class='ps_box-group psc_layout nuilp ' and contains(id,'win0divPTNUI_LAND_REC_GROUPLET$14')]"));
new Actions(TestBase.wDriver).dragAndDrop(from, to).build().perform();
System.out.println("Drag and Drop Completed");

WebDriver:Java - How to get all invsible buttons on webpage and click any one button

I am working on a web application which have the div structure as given below
<div class="hover-buttons">
<a id="j_idt59:0:j_idt62" href="javascript:void(0);" class=" btn btn-padding-side" ng-click="click($event,{s:"j_idt59:0:j_idt62",p:"j_idt56"});">
<i class="icon left "></i>
Transfer
</a>
<a id="j_idt59:0:j_idt64" href="javascript:void(0);" class=" btn btn-padding-side gray-dark" ng-click="click($event,{s:"j_idt59:0:j_idt64",p:"j_idt56",u:"breadcrumb mainPage accAddServicesPanel"});">
<i class="icon left "></i>
Account Details
<div scrolltopfunction=""></div>
</a>
</div>
I need to get all the buttons on the page with tag <a id> and click on any one button which have dynamic IDs changing.
The number of buttons displayed on page varies everytime logged In and these are invisible by default. Kindly advice on how to get all buttons and click any one button.
If you want random click from the list of WebElement try using java.util.Random as below :-
import java.util.Random;
Random random = new Random();
List<WebElement> list = driver.findElements(By.id("j_idt59"));
list.get(random.nextInt(list.size())).click();
Edited :- If want to click with certain condition instead of random click try as below :-
List<WebElement> list = driver.findElements(By.xpath("//*[contains(#id,'j_idt59')]"));
for(WebElement el : list){
if(el.getAttribute("id").contains("j_idt64")){
button.click();
break;
}
}
Get all links
Iterate over links & compare for link text you required
Here's the code snippet I think may help you:
List<WebElement> listOfButtons = driver.findElements(By.cssSelector("div.hover-buttons > a"));
for(WebElement button : listOfButtons){
if(button.getText().trim().equals("Your Button text")){
button.click();
}
}

Getting child elements using WebDriver

I've got the following HTML code:
<div class="ui-selectmenu-menu" style="z-index: 1; top: 251px; left: 37px;">
<ul class="ui-widget ui-widget-content ui-selectmenu-menu-dropdown ui-corner-bottom" aria-hidden="true" role="listbox" aria-labelledby="gwt-uid-191-button" id="gwt-uid-191-menu" style="width: 270px; height: auto;" aria-disabled="false" aria-activedescendant="ui-selectmenu-item-999">
<li role="presentation" class="ui-selectmenu-item-selected">
All Applications</li>
<li role="presentation" class="">
Option Alpha</li>
<li role="presentation" class="ui-corner-bottom">
Option Beta</li>
</ul>
</div>
...
<div class="ui-selectmenu-menu"...>...</div>
I'm able to get the WebElement for ui-selectmenu-menu like this (there are many on the page; hence, the use of findElements) :
List<WebElement> dropdowns = driver.findElements(By.className("ui-selectmenu-menu"));
And the ul below it like this:
WebElement ddChild = dropdowns.get(0).findElement(By.className("ui-selectmenu-menu-dropdown"));
I'm even able to grab all the li under the ddChild like this:
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li[*]"));
But the problem that I can't seem to figure out how to grab the text-value of the <a href="#nogo"... tag under each li element.
I'd like to be able to loop through all the ddOpts and grab the <a href="#nogo"... text values and save them to an ArrayList<String>.
So, for example, my first ArrayList<String> value would contain All Applications, then Option Alpha, then Option Beta, and then jump to the next ul element from the next dropdowns and do the whole process again, all while adding to the ArrayList<String>.
I'm sure its a simple solution but I've got limited experience with Selenium WebDriver.
Thanks!
PS: Is there a simple way to grab the child of a WebElement?
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li/a"));
ArrayList<String> links = new ArrayList<String>();
for(WebElement we : ddOpts) {
links.add(we.getText();
}
To extract the href attribute of the WebElement (referring to the anchor tag <a> in this example, do this:
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li/a"));
ArrayList<String> links = new ArrayList<String>();
for(WebElement we : ddOpts) {
// ADD all the href attribute strings to the list
links.add(we.getAttribute("href"));
}
This may also solve your problem:
List<WebElement> dropdowns = driver.findElements(By.className("x-combo-list"));
WebElement ddChild = dropdowns.get(0).findElement(By.className("x-combo-list-inner"));
List<WebElement> ddOpts = ddChild.findElements(By.xpath("//*[#id=\"x-auto-98\"]/div[4]"));
for(WebElement we:ddOpts){
System.out.println(we.getText());
if(we.getText().contains("ROLE_MANAGER")){
we.sendKeys("ROLE_MANAGER");
we.click();
break;
}
}
the below code will select the OptionAlpha in the dropdown of the above HTML code
driver.findElement(By.xpath("//*[#class='ui-selectmenu-menu')).click();
driver.findElement(By.xpath("//*[#class='ui-widget ui-widget-content ui-selectmenu-menu-dropdown ui-corner-bottom']//**[text()='Option Alpha']")).click();
Please try the below code to get all the links in the <a href
List<WebElement> allLis = driver.findElements(By.xpath("//*[#id='gwt-uid-191-menu']/li/a");
// Looping through above list using for-each loop
for(WebElement eachLi : allLis) {
System.out.println(eachLi.getText());
}
Hope this helps.
href="#nogo" is same for all the anchor tags, so it might create ambiguity in selecting the item by the method
dropdowns.findelement(By.linktext("#nogo"));

Categories

Resources