getText() method returns empty string - selenium

This is the HTML of the web page:
<td class=" gridCell wrapText " style="height:27px;" headers="a15" data-post="" title="">
<div class="oflowDivM ">
<span>
<script src="webwb/pzpega_control_text_12877380907.js!!.js" type="text/javascript"/>
<span class="leftJustifyStyle" data-ctl="Text">30,980,030.0000</span>
</span>
</div>
My intention is to extract the value 30,980,030.0000
I am using the following code:
driver.findElement(By.xpath("//td/div/span/span")).getText();
However, the getText() returns an empty string. The xpath is correct as I do not get NoSuchElementException. Could you please help in identifying my mistake here?

Can you please try below and see if value is printed or not:
driver.findElement(By.xpath("//td/div/span/span")).getAttribute("innerText");
If it still happens, can you try to have few seconds of wait and then try yo find element and get the text.

I probably think your element is hidden so getText() returns blank. The comment from #JeffC should fix your problem. Otherwise, try code below:
Thread.sleep(5000);
string text = driver.findElement(By.cssSelector("td > div span.leftJustifyStyle")).getAttribute("innerText");
or find only span which contains string that is longer than 2 characters
Thread.sleep(5000);
string text = driver.findElement(By.xpath("//td/div/span/span[string-length(normalize-space(text())) > 2]")).getAttribute("innerText");

Try this:
String details = "";
Thread.sleep(3000);
details = driver.findElement(By.xpath("//td/div//span")).getAttribute("value");

String amount = driver.findElement(By.xpath(".//*td[#class='gridCell wrapText']//div[#class='oflowDivM']//span//span[#class='leftJustifyStyle']")).getText();
This should work - just make sure class names are correct as in HTML...

From what I found out getText() sometimes returns empty string (if the element is hidden for example. I'm not sure if is or not the only case and neither about the cause).
Anyway what worked for me was getAttribute("textContent").
So how about something like :
driver.findElement(By.xpath("//td/div/span/span")).getAttribute("textContent");
?

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

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

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.

How to retrieve the value of an attribute using Seleium WebDriver?

The HTML code is given attached, I do not want to use hard code xpath, the requirement is to make it generic:
<td bgcolor="#FFFFFF">
<input name="hotel_name_0" id="hotel_name_0" type="text" value="Hotel Creek" class="select_text" onfocus="disable_ctrlV()" onkeypress="return Nothingonly(event)">
</td>
Code:
public static boolean fncVerifyTextInColumn(WebElement gridObjWebElement,
String stringToValidate, int columnNumber,String colName) {
boolean flagTextinColumn=false;
ArrayList<WebElement> objRows;
ArrayList<WebElement> objCols;
ArrayList<WebElement> childElement;
objRows=(ArrayList<WebElement>)gridObjWebElement.findElements(By.tagName("tr"));
objCols=(ArrayList<WebElement>)objRows.get(0).findElements(By.tagName("td"));
if(objCols.get(columnNumber).getText().equalsIgnoreCase(colName)){
for(int index=1;index<objRows.size();index++){
objCols=(ArrayList<WebElement>)objRows.get(index).findElements(By.tagName("td"));
childElement=(ArrayList<WebElement>)objCols.get(columnNumber).findElements(By.xpath("//input"));
System.out.println(childElement.get(0).getAttribute("value"));
if(stringToValidate.trim().equalsIgnoreCase(childElement.get(0).getAttribute("value").trim())){
flagTextinColumn=true;
}
}
}
return flagTextinColumn;
}
Method Calling:
fncVerifyTextInColumn(objGrid,hotels,1,"Hotel Name");
I would use cssSelector [id^='hotel_name_'] to locate the element and then getAttribute() retrieve the attribute value
By css = By.cssSelector("[id^='hotel_name_']");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(css));
System.out.println(myDynamicElement.getAttribute("value"));
Notice the regex search of cssSelector here. With ^ I am skipping any dynamic number. Hoping that's the only element with hotel_name_someNumber on the page.
Just do
String attValue = driver.findElement(byAnyMethod).getAttribute("AttributeName");
Hope it helps
I think what you are looking for is this. (I'm assuming you know how to code, you just need a general direction so I'm going to leave out specific code.)
First, find the table the td is in. You might need to use an xPath for this or you'll need to assign an ID to the table so you can locate it.
Then once you have the table, do a FindElements to get the list of TRs under it.
Once you have the TRs, you can loop through them, grab the TDs under that and grab the TD at the index that has the INPUT you want the value of, get the INPUT and then get it's value.
Yep, lots of steps.
A shortcut may be to class all of the inputs you want the value for with a unique class and do a FindElements By className and loop through that list.

Element not found in the cache - perhaps the page has changed since it was looked up - Command duration or timeout

All I am trying to achieve is an assertion, that text entered in the description field displays after the update button is hit, but I am getting an error that I mentioned in the Title above. Any help is greatly appreciated!
FYI - page does refresh after user hits the update button, however, I don't notice any change in the url though!
My code:
//send text to the description text field
WebElement description = driver.findElement(By.id(PvtConstants.UPDATE_KEYNAME_DESCRIPTION_FIELD));
description.sendKeys(keyname_description);
//verify the text (this is the assertion)
verifyDisplay(description.getAttribute("textContent") + "", By.id(PvtConstants.UPDATE_KEYNAME_DESCRIPTION_FIELD));
HTML:
<li>
<span>2.</span>
<label class="input_label" for="keyname_description">Description</label>
<textarea style="line-height:normal;" id="keyname_description" name="description" maxlength="256">this is my description text</textarea>
</li>
In case of text field or text area, you need to get values using the attribute value. **description.getAttribute("value")**. I guess this is throwing the error as it could not find the attribute textContent.
Use Javascript Executor to get the text from text area.Let me know if this code doesn't work for you.
JavascriptExecutor js=(JavascriptExecutor) driver;
String description_text=(String) js.executeScript("return document.getElementById('keyname_description').innerHTML");
System.out.println(description_text);