Using Selenium to select text - selenium

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.

Related

How to construct an XPath which remove text from <br> tag?

I am trying to fetch text before the <br> tag using XPath & Java. I tried multiple solutions, but had no luck yet.
//div[#class="help-block"]/p[count(preceding-sibling::br) < 1]
This is my HTML code:
<div class="help-block">
<p>
This is sample text
<br>
Text after a breakpoint
</p>
</div>
Expected outcome: This is sample text.
Actual outcome: This is sample text Text after a breakpoint
To get the This is sample text Induce WebDiverWait And visibilityOfElementLocated() And get the element.
Induce JavascriptExecutor And get the textContent of firstChild
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element=wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#class='help-block']/p")));
JavascriptExecutor js = (JavascriptExecutor) driver;
System.out.println(js.executeScript("return arguments[0].firstChild.textContent;",element));
I think you can just run this:
driver.find_element_by_xpath("//p[br]").text
This will get the <p> element, but the query also checks to make sure that <p> contains a <br> element inside it. So you are just getting the <p>, and .text should get the text from the <p>.
Your expression was close. But you didn't take into account that p is only one element and you want subnodes of p. So change your expression to the following (also escaping the < char)
//div[#class="help-block"]/p/node()[count(preceding-sibling::br) < 1]
It's output is:
This is sample text

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
}
}

Locating Element with same class in Selenium using c#

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
}
}

Selenium clicking a sub menu

I am Really stuck for the past two days here. I am trying to click sub menu and when I try to click sub menu I get an errors as like the following
Element not found for the sub menu.
I have tried below code
WebElement element = driver.findElement(By.id("x-menu-el-P46915788081933044__folderbrowser_PJL"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
HTML Code
<li id="x-menu-el-P46915788081933044__folderbrowser_PJL" class="x-menu-list-item">
<a id="P46915788081933044__folderbrowser_PJL" class="x-menu-item" href="javascript:var abc = doNothing()" unselectable="on" hidefocus="true">
<img id="ext-gen926" class="x-menu-item-icon " src="netmarkets/images/import.gif">
<span id="ext-gen927" class="x-menu-item-text">Upload Documents from Compressed File</span>
Instead of using the ID you should probably use the class name.
WebElement element = driver.findElement(By.ClassName("x-menu-list-item"));
or you could try using the css selector
WebElement element = driver.findElement(By.cssSelector("li[class='x-menu-list-item']"));
Since the above return multiple items you could just use to return the exact element that you need:
WebElement element = driver.findElement(By.linkText("Upload Documents from Compressed File"));
1st click on the menu and then try the following statement -
driver.findElement(By.xpath("//li[#class='x-menu-list-item']//span[contains(text(),'Upload Documents from Compressed')])).click();
or directly try this -
driver.findElement(By.xpath("//span[contains(text(),'Upload Documents from Compressed')])).click();
I guess mostly the error is due to the span name spaces in between words, if the above dont work, pls attach a screenshot or give some details of the html code, so we can try more options, all d best.

Using Selenium, xpath gets tags but text is empty

I'm using Selenium WebDriver to fetch a bunch of tags via XPATH. The xpath successfully finds the tags, but the "Text" attribute for the returned IWebElements is empty.
Here's the HTML:
<ul>
<li id="foo1">someValue</li>
<li id="foo2">someOtherValue</li>
</ul>
And the xpath:
//ul/li[startswith(#id, 'foo')]
Any ideas? The Xpath definitely grabs the right elements, but the Text element is empty.
Try this code to get the text of 2nd element - <li id="foo2">someOtherValue</li>
:
WebElement fooEle = driver.findElement(By.xpath("//descendant::ul/li[starts-with(#id,'foo')][2]"));
String fooEleText = fooEle.getText();
System.out.println("foo Element Text -" + fooEleText); //should print expected text "someOtherValue"
Note- if you want to get the 1st element text, then change the index value of the xpath
That is, //descendant::ul/li[starts-with(#id,'foo')][1]