Locating Element with same class in Selenium using c# - selenium

I am trying to access ABC. I know that simple By.ClassName("bb") will not work here. How else can I access this content.
<body>
<div id="Frame">
<div class="bb"></div>
<div class="bb">ABC</div>
</div>
</body>

You can use the below css selector to get the value of "ABC".
.bb:nth-child(2)

You can use "XPath" Expression to find or locating your element.
Example : element = findElement(By.xpath("Your xpath expression");
For your XML use following line.
element = findElement(By.xpath("/body/div/div[#class='bb'][node()]");

There is a way to do this in the search using XPath but I am not an XPath expert. I can give you a solution using CSS Selectors. Basically you grab all the DIVs with class bb and then search their text to find the desired text.
String searchText = "ABC";
IReadOnlyCollection<IWebElement> divs = driver.FindElements(By.CssSelector("div.bb"));
foreach (IWebElement div in divs)
{
if (div.Text == searchText)
{
break; // exit the for and use the variable 'div' which contains the desired DIV
}
}

Related

How to Send Text to Text Box which have same xpath

In Selenium Webdriver we have three Text boxes. All the text boxes have the same Id, and I want to send some text in the second text box.
This is my code:
Driver.findElements(By.xpath("//*[#id='testInstanceScan']"));
Could anyone please help how to handle Text boxes which have same Id ?
Currently i m using below code which always send same text for all the three text boxes.
List<WebElement> textfield1 = Driver.findElements(By.xpath("//*[#id='testInstanceScan']"));
for(int i=0; i<textfield1.size();i++){
WebElement local_textfield1=textfield1.get(i);
String value1=local_textfield1.getAttribute("placeholder");
if(value1.equalsIgnoreCase(""))
{
local_textfield1.sendKeys("Amarendra Singh");
}
}
There are two ways to get the second textbox.
Method 1: using find elements
List<WebElement> textfields = Driver.findElements(By.xpath("//*[#id='testInstanceScan']"));
textfields.get(1).sendKeys("Amarendra Singh");
Method 2: using xpath
WebElement textfield2 = Driver.findElements(By.xpath("(//*[#id='testInstanceScan'])[2]"));
textfield2.sendKeys("Amarendra Singh");
You can use an array like trick to access each element matching the XPath
WebElement textField1 = driver.findElements(By.xpath("(//*[#id='testInstanceScan'])[1]"));
WebElement textField2 = driver.findElements(By.xpath("(//*[#id='testInstanceScan'])[2]"));
The quickest and easiest way I know to do this is to use an XPath to specify the expected ID and placeholder = "" and then specify the index of the element you want.
Given an HTML example of
<html>
<div id="testInstanceScan" placeholder="">e1</div>
<div id="testInstanceScan" placeholder="">e2</div>
<div id="testInstanceScan" placeholder="">e3</div>
</html>
The code below works
List<WebElement> searchBox = driver.findElements(By.xpath("//div[#id='testInstanceScan'][#placeholder='']"));
System.out.println(searchBox.get(1).getText());
and returns
e2
which is the element that contains the desired ID, empty placeholder attribute value, and is the second element. This form of XPath can be tailored to a lot of different situations to get the desired element in a single pass instead of looping or filtering the collection.
In your case, your final code would look like
List<WebElement> textfields = driver.findElements(By.xpath("//input[#id='testInstanceScan'][#placeholder='']"));
textfields.get(1).sendKeys("Amarendra Singh");
If that still doesn't work, you may need a wait.
By locator = By.xpath("//input[#id='testInstanceScan'][#placeholder='']");
List<WebElement> textfields = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(locator));
textfields.get(1).sendKeys("Amarendra Singh");
I don't know exactly what is yoyr question but what i understand you want to perform operation on textbox which have same xpaths
This is a sample Html which I used for example
<html>
<div id="test" placeholder="">element1</div>
<div id="test" placeholder="">element2</div>
<div id="test" placeholder="">element3</div>
<div id="test" placeholder="">element4</div>
</html>
First use findElements() to extract all elements and then use if loop to select one and perform operation This is my code
WebDriver driver=new FirefoxDriver();
driver.get("URL");
List<WebElement> allElements=driver.findElements(By.xpath("//div[#id='test']"));
for (WebElement tempElement : allElements) {
if(tempElement.getText().equalsIgnoreCase("element2"))
{
System.out.println(tempElement.getText()); // you can perform your operations
}
}

Finding a parent element in webdriver.io

I've seen a couple of solutions in the original webdriver that use getAttribute('xpath') and append to that '/..' but webdriver.io doesn't have an xpath attribute so I haven't been able to use that. Any ideas on how to grab the parent element?
The case I am trying to test is inside of a bootstrap layout and the element that is actually getting the class I am trying to check is one above. It looks like this:
<div class="form-group">
<input class="form-control" type="text" name="username">
<other stuff>
</div>
I am selecting by driver.element("input[name='username'"] but the error class actually hits the div
<div class="form-group error">
<input class="form-control" type="text" name="username">
<other stuff>
</div>
So I need to check if the div itself has an error class, not the input I can find (there are no uniques on the div)
Any help would be greatly appreciated.
Just searched the same and found this by inspecting Webdriver.IO source code - you can use el.$('..') to get the parent element, like this:
$('input[name="username"]').$('..') // returns the parent element
Voila! It's a part of their XPath selectors support.
I ended up solving this by using execute to get the xpath from jQuery, here is the code I used (albeit for a different test I was writing - if every label that has a * is a required field). Hopefully this is helpful to somebody in the future:
var requiredXPaths = browser.execute(function () {
var returner = [];
var $elements = $('.modal.fade.in').find("label:contains('*')");
_.each($elements, el => {
var xpath = '';
var element = el.parentElement;
for (; element && element.nodeType == 1; element = element.parentNode) {
var id = $(element.parentNode).children(element.tagName).index(element) + 1;
id > 1 ? (id = '[' + id + ']') : (id = '');
xpath = '/' + element.tagName.toLowerCase() + id + xpath;
}
returner.push(xpath);
});
return returner;
});
I got the xPath function from another stackoverflow page (How to calculate the XPath position of an element using Javascript?)
WebdriverIO actually lets you use XPath in your selectors, so any valid Xpath selector should work to find the element you want.
Alternatively, you could just use isExisting to check if the element exists on the page using the error class parent:
driver.isExisting('.error input[name="username"]');
If the element doesn't exist, then your error class didn't get added.
I've been talking about this in gitter, when the parent can be selected input[name="username"]
The parent of this element can be selected as //div[input[name="username"]]

Using selenium, how to select a the text in a paragraph which is nested in a div element?

Sample code:
<div class="loginbox">some code</div>
<div class="loginbox">other code</div>
<div class="loginbox">
<p> style="color: Red;">Test Extract</p>
</div>
Using Selenium Web Driver, I would like to extract the text Test Extract within the paragraph element which is nested within a div, whose class name is shared with other div classes. c# preferred.
You can try below method:
driver.findElement(By.xpath("//div[#class='loginbox']/p")).getText();
EDITED
You should use = inside the square braces like:
driver.findElement(By.xpath("//div[#class='loginbox']/p");
C# code to get the text from the locator specified,
IWebElement element = Browser.GetElementByCssSelector("div.loginbox p");
string text = element.Text;

Using Selenium to select text

Want to select the text "This is for testing selector" from below HTML code.
<div class="breadcrumb">
<a title=" Home" href="http://www.google.com/"> Home</a>
<span class="arrow">»</span>
<a title="abc" href="http://www.google.com/">test1</a>
<span class="arrow">»</span><a title="xyz" href="http://www.google.com/">test2</a>
<span class="arrow">»</span>
This is for testing selector
</div>
I'm not sure if there an easy way out for this or not. It turned out to be more difficult than I thought. Below mentioned code is tested locally and giving correct output for me ;)
String MyString= driver.findElement(By.xpath("//div[#class='breadcrumb']")).getText();
//get all child nodes of div parent class
List<WebElement> ele= driver.findElements(By.xpath("//div[#class='breadcrumb']/child::*"));
for(WebElement i:ele) {
//substracing a text of child node from parent node text
MyString= MyString.substring(i.getText().length(), MyString.length());
//removing white spaces
MyString=MyString.trim();
}
System.out.println(MyString);
Let me know if it works for you or not!
Try with this example :
driver.get("http://www.google.com/");
WebElement text =
findElement(By.className("breadcrumb")).find("span").get(1);
Actions select = new Actions(driver);
select.doubleClick(text).build().perform();
I suggest also that you copy the xpath for the text you need and put it here to have the exact xpath
You cannot select text inside an element using xpath.
Xpath can only help you select XML elements, or in this case, HTML elements.
Typically, text should be encased in a span tag, however, in your case, it isn't.
What you could do, however, is select the div element encasing the text. Try this xpath :
(//div[#class='breadcrumb']/span)[3]/following-sibling::text()
You could try Abhijeet's Answer if you just want to get the text inside. As an added check, check if the string obtained from using getText() on root element contains the string obtained from using getText() on the child elements.

Finding all "A" tags with specific strings in the attribute href?

driver.FindElement(By.Name("zipcode")).Clear();
driver.FindElement(By.Name("zipcode")).SendKeys(zipcode);
driver.FindElement(By.Name("Go")).Click();
driver.FindElements(By.TagName("A"). //<---- ?????????
I have some Selenium API code that I started. I aim to get all the "A" tags with the string "alertsepy" and the sting "sevendwarves" in the attribute href and return all those elements into an array so I can do some further processing. I started the code but I am really not quite sure how to get all the way there yet. Does anyone know how to do this type of query with Selenium.
Kind Regards!
You should use css selector:
IList<IWebElement> elements = driver.findElements(By.cssSelector("a[href*=alertsepy],a[href*=sevendwarves]")
This query will return a nodes with href attribute that contains alertsepy or sevendwarves or both strings:
<a href="alertsepy.html" > </a>
<a href="sevendwarves.html" > </a>
<a href="http://sevendwarves.org/alertsepy.html" > </a>
Or you can use:
IList<IWebElement> elements = driver.findElements(By.cssSelector("a[href*=alertsepy][href*=sevendwarves]")
This query will return a nodes with href attribute that contains alertsepy and sevendwarves strings:
<a href="http://sevendwarves.org/alertsepy.html" > </a>
For a list of generally available css selectors refer to w3c css selectors. For the list of available in Selenium query types refer to Locating UI Elements.
List<WebElement> anchortaglist = driver.find Elements(By.Tag Name('a');