How to select specific element form list by using Selenium WebDriver? - selenium

Can anyone guide me how to select specific element from list view
from using below code.
<div id="menu" class="tabalign k-widget k-reset k-header k-menu k-menu-horizontal" data-role="menu" tabindex="0" role="menubar" aria-activedescendant="menu_mn_active">
<li class="k-item k-state-default k-first mainMenu2" role="menuitem" id="menu_mn_active"><span class="k-link"><img class="k-image" alt="" src="/Images/Common/Module_2.png"><span id="2">Profiles</span></span></li>
<li class="k-item k-state-default mainMenu3" role="menuitem"><span class="k-link"><img class="k-image" alt="" src="/Images/Common/Module_3.png"><span id="3">Contacts</span></span></li>
And I have tried below code but it is not worked for me:
WebElement element = driver.findElements(By.xpath("//*[#id=\"menu_mn_active\"]"));
element.click();

Try this code in Java (it selects first element from dropdown):
driver.findElement(By. id("menu")).click();
List<WebElement> options = driver.findElements(By. cssSelector(".k-item.k-state-default"));
for (WebElement opt : options) {
if (opt.getText().equals("Profiles")) {
opt.click();
}
}

You can use like this:
First get location of all elements:
List<WebElement> element = driver.findElements(By.xpath("//*[#id=\"menu_mn_active\"]"));
For the first element:
element.get(0).click(); // for first element
For the second element:
element.get(1).click(); // for second element

Related

how to verify the drop down value using asserts in selenium when the HTML element is not Select class

i have an HTML element which is not select element. so i want to verify all the dropdown list using soft assert.
This is the code which i tried but it works only for select HTML element.
String[] exp = {"--None--","Open","Closed","Priority-Reopened","Researching","Updated","Escalated"};
WebElement dropdown = threadWebDriver.get().findElement(By.id("ddlNights"));
Select select = new Select(dropdown);
List<WebElement> options = select.getOptions();
for(WebElement we:options)
{
boolean match = false;
for (int i=0; i<exp.length(); i++){
if (we.getText().equals(exp[i]){
match = true;
}
}
Assert.assertTrue(match);
}
HTML element for this is given below:-
<a aria-required="true" class="select" aria-disabled="false" aria-describedby="2295:0-label" aria-haspopup="true" tabindex="0" role="button" title="" data-aura-rendered-by="2305:0" href="javascript:void(0);" data-interactive-lib-uid="9">Open</a>
How i can verify the list of drop down values?
I would take another approach of checking if the dropdown have any of the values specified using xpath like this.
//*[#id='ddlNights'][contains('--None--,Open,Closed,Priority-Reopened,Researching,Updated,Escalated',a)]
Screenshot:
You can check if the element exist with the above xpath. That validates true if any of the list items present otherwise it will be false. You have to handle that assertion using softAssertion.

trouble making in xpath for "ul" html code in selenium webdriver

HTML code:
<div id="routingPanel" class="">
<div id="routingPanelRight">
<ul id="routingList" class="ui-sortable">
<li class="ui-menu-item ui-draggable" style="display: list-item;" role="presentation" data-type="srl" data-id="15">
<a class="ui-corner-all" tabindex="-1">AS-HTTS-US-LAN-SW</a>
<span class="fa fa-trash"/>
<span class="type">[srl]</span>
</li>
<li class="ui-menu-item ui-draggable" style="display: list-item;" role="presentation" data-type="queue" data-id="119">
<a class="ui-corner-all" tabindex="-1">AS-EMEA-NORTH</a>
<span class="fa fa-trash"/>
<span class="type">[queue]</span>
</li></ul></div></div>
I need to click on a button which is having the span class"fa fa-trash" but it is inside li class. And i have list on buttons on the page with li class changing.
I am giving testdata from excel file so i can't use the direct value.
i tried to use this xpath
.//*[#id='routingList']/li[5]/span[1] //testdata1
.//*[#id='routingList']/li[2]/span[1] //testdata2
where li value changes everytime from excel file.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated((By.xpath("//ul[#id='routingList']/li/span[1]")))).click();
List<WebElement> options = driver.findElements(By.xpath("//ul[#id='routingList']/li/span[1]"));
for (WebElement option : options) {
if(testData.equals(option.getText()))
option.click();
Tried above code but it is deleting only one from the list ,where i have passed two more testdata that needs to be deleted.
Need suggestions Please
According to the information you gave me in comments, I think the problem is that you are trying to get a text from an element that doesn't contain text.
Let's say your testData is AS-HTTS-US-LAN-SW. In the HTML you provided and the xpath you mentioned, you are selecting an autoclosing tag <span class="fa fa-trash"/>. Once this tag is selected, you are trying to get the text inside of it, and there is none.
<ul id="routingList" class="ui-sortable">
<li class="ui-menu-item ui-draggable" style="display: list-item;" role="presentation" data-type="srl" data-id="15">
===========================
<a class="ui-corner-all" tabindex="-1">AS-HTTS-US-LAN-SW</a> ----> The text is contained here
<span class="fa fa-trash"/> ---> No text in that tag
===========================
<span class="type">[srl]</span>
</li>
</ul>
So, basically, you have to modify a little bit your xpath from : //ul[#id='routingList']/li/span[1] to : //ul[#id='routingList']/li/a to get the text, and then go back to the parent node to find your button with : ../span[contains(#class, 'fa fa-trash')]
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated((By.xpath("//ul[#id='routingList']/li/span[1]")))) // removed the click here because you were clicking on the first element of the list
List<WebElement> options = driver.findElements(By.xpath("//ul[#id='routingList']/li/a"));
for (WebElement option : options) {
if(testData.equals(option.getText()))
option.findElement(By.xpath("../span[contains(#class, 'fa fa-trash')]")).click();
Tell me if it helped
I know you already accepted an answer but there's a more efficient way to do this. You can specify the text you are looking for as part of the XPath. So, you do a single search instead of looping through all the options which can be a performance hit if there are many options. Also, with something like this you are likely to use it more than once so put it in a function.
In this case, the function would take in the string you are looking for and then click the appropriate element.
public void selectRegion(String regionName)
{
driver.findElement(By.xpath("//a[.='" + regionName + "']/following-sibling::span[#class='fa fa-trash']")).click();
}
and you would call it like
selectRegion(testData);
The function looks for an A tag that contains the desired text and then clicks the sibling SPAN with class fa fa-trash.

Drop Down value in selenium using java

Could you please help me in selecting drop down value in selenium using java code.
My issue is that in HTML code, i do not have SELECT class.
This is the code i have tried :
List<WebElement> elements = driver.findElement(By.id("Some Value"));
for (WebElement element: elements){
new Actions(driver).sendKeys(Keys.Arrow_Down).perform();
if(Element.getText().equals("Cliam Document")){
element.click();
}
}
Below is html snippet :
<input class="dijitReset dijitInputInner" autocomplete="off" data-dojo-attach-point="textbox,focusNode" role="textbox" aria-autocomplete="both" aria-required="true" tabindex="0" id="ecm_widget_AddContentItemGeneralPane_0_entryTemplateSele‌​‌​ctor" value="" aria-invalid="true" type="text">
<span class="dijitPlaceHolder dijitInputField">Enter or select an entry template</span>
<input name="ecm_widget_AddContentItemGeneralPane_0_entryTemplateSe‌​‌​lector" value="" type="hidden"></div>
you can try following code (Here I'm assuming that dropdown options appear after clicking the dropdown field):
WebElement yourDropdown = driver.findElement(By.cssSelector("#ecm_widget_AddContentItemGeneralPane_0_entryTemplateSele‌​‌​ctor"));
yourDropdown .click();
List<WebElement> elements = driver.findElements(By.cssSelector("#ecm_widget_AddContentItemGeneralPane_0_entryTemplateSele‌​‌​ctor input"));
for (WebElement element: elements){
if(Element.getText().equals("Cliam Document")){
element.click();
}
}
Follow these steps:
Step 1: Enter value in the input field.
driver.findElement(By.xpath("Enter xpath here")).sendkeys("enter text here");
Step 2: Now to select value from the list
List<WebElement> elements = driver.findElements(By.xpath("Some Value"));
for (WebElement element: elements){
String element_text = element.gettext();
if(element_text.equals("Cliam Document")){
element.click();
}
}
Follow Below steps, will be able to select value from dropDown
Step 1.
WebElement dropdownTab = driver.findElements(By.xpath("dropdown locator")).click(); //Click on the dropdown tab
Step2:
List options = driver.findElements(By.tag_name('option')); //Get all the options
Step 3:
for (WebElement element: options){
if(options.getText().equals("Text Name which needs to be selected")){
element.click();
break;
}
}
This should work, if still you are facing issue - Please provide the url where you are trying...will post the exact code

No such element Exception. class name with double__

I am trying to get the text under the tag. That is Arduus, Gstaad, Switzerland. I tried with the classname and also with xpath.
driver.findElement(By.className("chalet-details__title"));
String chaletTitle = driver.findElement(By.xpath("//div/h1[#class='chalet-details_title']")).getText();
But its giving NoSuchElementException. The classname has double underscore(__) .Is it because of that not working? Can anyone help me with this?
<div class="col-md-12 col-sm-12 col-xs-12">
<h1 class="chalet-details__title">
<span class="chalet-details__title-property">Arduus</span>,
<a class="chalet-details__title-resort" href="/ski- resorts/switzerland/gstaad">Gstaad</a>,
<a class="chalet-details__title-country" href="/ski- resorts/switzerland">Switzerland</a>
</h1>
<div class="chalet-details__rating">
<div class="chalet-details__wrapper">
<span class="chalet-details__star" style="width: 108px;"></span>
<span class="chalet-details__mask"></span>
</div>
</div>
</div>
You can try something like:
driver.findElement(by.cssSelector("h1.chalet-details__title"))
I just tried this and it worked fine with the provided html, if this still fails for you, can you verify that there aren't any iframes on the page.
Both your locators are OK, but you might need to wait for your element to be present in DOM:
WebDriverWait wait= new WebDriverWait(driver,20 );
String chaletTitle = wait.until(ExpectedConditions.presenceOfElementLocated(By.className("chalet-details__title"))).getText();
Another reason for NoSuchElementException: your element could be located inside an iframe, so you need to switch to that frame before handling target element:
driver.switchTo().frame("iframeNameOrId");
If it has no attributes as id or name:
WebElement someFrame = driver.findElement(By.xpath("//iframe[#someAttr='someValue']"));
driver.switchTo().frame(someFrame);
To get all the text under h1 tag find all elements using locator as follows:
List<WebElement> items = driver.findElements(By.cssSelector("h1.chalet-details__title > *")); //it will find all elements immediately under the h1 tag
Now, iterate over the elements.
Complete code:
List<WebElement> items = driver.findElements(By.cssSelector("h1.chalet-details__title > *"));
for(WebElement item : items){
System.out.println(item.getText());
}

Identifying the Web element with same class name in Selenium

I have tried to get the number of tweets(tweet count) through selenium
Here is the page source:
<li class="DashboardProfileCard-stat Arrange-sizeFit">
<a class="DashboardProfileCard-statLink u-textUserColor u-linkClean u-block"
title="1 Tweet"
href="/saisiva14"
data-element-term="tweet_stats">
<span class="DashboardProfileCard-statLabel u-block">Tweets</span>
<span class="DashboardProfileCard-statValue" data-is-compact="false">1</span>
</a>
</li>
<li class="DashboardProfileCard-stat Arrange-sizeFit">
<a class="DashboardProfileCard-statLink u-textUserColor u-linkClean u-block"
title="38 Following"
href="/following"
data-element-term="follower_stats">
<span class="DashboardProfileCard-statLabel u-block">Following</span>
<span class="DashboardProfileCard-statValue" data-is-compact="false">38</span>
</a>
</li>
<li class="DashboardProfileCard-stat Arrange-sizeFit">
<a class="DashboardProfileCard-statLink u-textUserColor u-linkClean u-block"
title="4 Followers"
href="/followers"
data-element-term="following_stats">
<span class="DashboardProfileCard-statLabel u-block">Followers</span>
<span class="DashboardProfileCard-statValue" data-is-compact="false">4</span>
</a>
</li>
I could not able to locate the web element for getting Tweets,Followers & following. The reason is span class names are common for all these elements.Please help me .
To get number of Tweets/ Following/ Followers, You can try the below statements:
System.out.println(driver.findElement(By.xpath("//a[contains(#title, 'Tweet')]/span[2]")).getText());
System.out.println(driver.findElement(By.xpath("//a[contains(#title, 'Following')]/span[2]")).getText());
System.out.println(driver.findElement(By.xpath("//a[contains(#title, 'Followers')]/span[2]")).getText());
To click on the Tweets/ Following/ Followers links, You can try the below statements:
driver.findElement(By.xpath("//a[contains(#title, 'Tweet')]")).click();
driver.findElement(By.xpath("//a[contains(#title, 'Following')]")).click();
driver.findElement(By.xpath("//a[contains(#title, 'Followers')]")).click();
or
driver.findElement(By.xpath("//a[./span[text()='Tweets']]")).click();
driver.findElement(By.xpath("//a[./span[text()='Following']]")).click();
driver.findElement(By.xpath("//a[./span[text()='Followers']]")).click();
The above statements are working fine for me.
try this
IList<IWebElement> elements = driver.FindElements(By.ClassName("DashboardProfileCard-stat"));
foreach (IWebElement element in elements)
{
IWebElement ele = element.FindElement(By.ClassName("DashboardProfileCard-statLabel"));
if (ele.Text == "Tweets")
{
return element.FindElement(By.ClassName("DashboardProfileCard-statValue")).Text;
}
}
this is using C#, you can modify accordingly if anyother language is used.
The selector .DashboardProfileCard-stat span:nth-child(2) should give you the collection of web elements pointing to the count. For example in Java:
ArrayList<WebElement> elements = driver.findElements(By.cssSelector(".DashboardProfileCard-stat span:nth-child(2)"))
Then you can use elements.get(0).getText() for tweets. elements.get(1).getText() for following. elements.get(2).getText() for followers. So:
ArrayList<WebElement> elements = driver.findElements(By.cssSelector(".DashboardProfileCard-stat span:nth-child(2)"));
int tweets = elements.get(0).getText();
int following = elements.get(1).getText();
int followers = elements.get(2).getText();
Of course, do your appropriate safety checks, etc. Check the length of the array before access.
This code is in Java :)
capture all the parents of the "SPAN" into a collection item.
Iterate on the collection to find the span elements (which are child of <a> tag) and capture text based on the class name variation statLabel / statValue".
List<WebElement> webElement = driver.findElements(By.xpath("//li[#class='DashboardProfileCard-stat Arrange-sizeFit']//a"));
for (WebElement element : webElement) {
System.out.println(element.findElement(By.xpath("//span[contains(#class,'statLabel')]")).getText());
System.out.println(element.findElement(By.xpath("//span[contains(#class,'statValue')]")).getText());
}