Identifying the Web element with same class name in Selenium - 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());
}

Related

Element with locator not found. Tried Xpath and CSS selector

Tried using xpath locator and css on the page neither worked
I tried the following with xpath:
#Wait Until Page Contains Element //a[contains(text(), 'Service Clusters')]
Also tried the following:
#Click Element //div[#id='austabsserviceTabs']/ul/li[2]/a
And css selector
Wait Until Page Contains Element css=a[href='#austabsserviceTabs-1']
Click Element css=a[href='#austabsserviceTabs-1']
However I got the same error for all attempts: Element '//a[contains(text(), 'Service Clusters')]' not found.
Here is the HTML from the page, I'm trying to select the "Service Clusters" tab:
<ul class="ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all">
<li class="ui-state-default ui-corner-top">
Service Profiles
</li>
<li class="ui-state-default ui-corner-top ui-tabs-selected ui-state-active">
Service Clusters
</li>
<li class="ui-state-default ui-corner-top">
Service Globals
</li>
</ul>
You can either choose the class attribute for your Service cluster or your href attribute. It's upto you. I've tested out the xpath for your given html and I've found this //a[#class='ausTabLabel'] Xpath to be valid for your Service Cluster. If you want to choose the href attribute then you can do something like //a[#href='#austabsserviceTabs-1']
The thing with Xpath is that you can choose anything you want in your html. If you need further guidance in xpath check out this website : https://www.guru99.com/xpath-selenium.html.
try on this way may be it help you.
var ul = driver.findElements(By.XPath("//ul[contains(#class,'ui-tabs-nav')]")).ToList();
for (int i = 0; i < ul.Count; i++)
{
var Li = ul[i].FindElements(By.TagName("li")).ToList();
foreach (IWebElement item in Li)
{
if (item.Text == "Service Clusters")
{
//here do whatever you want to do
//break; if you want.
}
}
}

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

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

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.

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());
}

WebDriver: find element by CSSSelector or XPath

I have a problem to get element <i class="angle-up"></i> on the following page. The selection should be depended on "data-id" value. Thanks in advance.
<li class="recent" data-to="3" data-off="23" data-id="5">
<a class="collapse in" href="/board">
<span>
Board
</span>
<i class="angle-up"></i>
</a>
</li>
<li class="" data-to="3" data-off="23" data-id="7">
<a class="collapse in" href="/set">
<span>
Set
</span>
<i class="angle-up"></i>
</a>
</li>
Well I think if the value is data-id dependant then you might need to split the Xpath or Css selector in 3 parts as below:
Part1=//li[#data_id='
Part2= (Fetch this value at runtime using an appropriate variable)
Part3= ']//i[#class='angle-up']
and now you may use the following code to use the element
public class TestElement {
public static void main(String args[])
{
WebDriver driver= new FirefoxDriver();
driver.get(YOUR INTERNAL URL HERE.);
String elementPart1=//li[#data_id='
String elementPart2=5 //keeping the id you are looking for
String elementPart3=']//i[#class='angle-up']
WebElement element = driver.findElement(By.xpath(elementPart1+elementPart2+elementPart3);
}
}
Here as you may see one example of such xpath could be
//li[#data_id='5']//i[#class='angle-up']
Also if I would advise you to check using firefinder which is a firebug extension to verify that the xpath is correct.