Can anyone help me to read a label text from selenium webdriver
The for attribute value and label text are entirely different
Assuming the label looks in HTML something like this:
<span id="spannyspan" title="the Title of SPAN">The Text</span>
then the WebElement will be best approached like this:
WebDriver driver = new FirefoxDriver();
WebElement theSpan = driver.findElement(By.id("spannyspan"));
String title = theSpan.getAttribute("title");
String label = theSpan.getText();
System.out.println(title); // will return "the Title of SPAN"
System.out.println(label); // will return "The Text"
// both without apostrophes ofcourse
If this does not help please provide sample HTML of label which you are trying to fetch
Suppose there is a label contain text "hello":
<label>hello</label>
then what you have to do is:
# first find this element using xpath or css locator and store that into WebElement object:
WebElement label = driver.findElement(By.xpath("//label[contains(text(),'hello')]");
# After that using getText() method you can get the text of the label element.getText() method return value in string so,store the value in the string variable
String lbltext = label.getText();
# After that if you want to print the value then
System.out.println("text = "+lbltext);
Related
I have two span elements and I need to check that my text: Frat Brothers (2013) is equal to text inside this span clases and that click on this element.
<a href="/frat-brothers" class="">
<span class="name-content-row__row__title">Frat Brothers</span>
<span class="name-content-row__row--year">(2013)</span>
</a>
My code:
String title = "Frat Brothers (2013)";
List<WebElement> content = driver.findElements(By.cssSelector("span[class*='name-content-row__'"));
for (WebElement e : content) {
System.out.println("elememts is : " + e.getText());
if (e.getText().equals(title)) {
click(e);
}
output:
elememts is : Frat Brothers
elememts is : (2013)
if statment isn't executed.
if statment did not execute, cause you have
String title = "Frat Brothers (2013)";
change that to
String title = "Frat Brothers";
and you should be good to go.
also do not use click(e); instead it should be e.click();
driver.findElements method accepts By parameter while you passing it a String.
In case you want to select elements according to this CSS Selector you can do this:
List<WebElement> content = driver.findElements(By.cssSelector("span[class*='name-content-row__'"));
Also, you will get 2 span elements, first with text Frat Brothers and second with text (2013).
No one of these elements text will NOT be equal to Frat Brothers (2013).
You can check if title contains these texts
You can try the following xPath: //a[normalize-space()='Frat Brothers (2013)']
So that there would be no need for extra code. Like:
String title = "Frat Brothers (2013)";
WebElement content = driver.findElement(By.xpath("//a[normalize-space()='" + title + "']"));
content.click();
P.S. - Here is the xPath test: http://xpather.com/V9cjThsr
Text verification, add testng dependency in your pom.xml
String title = "Frat Brothers (2013)";
// storing text from the element
String first = driver.findElements(By.cssSelector("span[class*='name-content-row__'")).get(0).getText();
String second = driver.findElements(By.cssSelector("span[class*='name-content-row__'")).get(1).getText();
// validating the text
Assert.assertTrue(title.contains(first), "checking name is available in the element");
Assert.assertTrue(title.contains(second), "checking year is available in the element");
I'm trying to verify a few things on a page and have a grid with header columns. I want to grab the text from those are part of the verification. For some reason it's returning empty and I don't understand why considering I'm using contains text to find the element.
String expectedName = "Employee Name";
String actualName = driver.findElement(By.xpath("//div[contains(text(), 'Employee Name')]")).getText();
Assert.assertEquals(expectedName, actualName);
The error I get is this: java.lang.AssertionError: expected [Employee Name] but found []
The HTML:
<div class="dx-datagrid-text-content dx-text-content-alignment-left dx-header-filter-indicator" role="presentation">Employee Name</div>
You seem to be close. To extract the textContent of the <div> element ideally you need to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:
cssSelector:
String expectedName = "Employee Name";
String actualName = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.dx-datagrid-text-content.dx-text-content-alignment-left.dx-header-filter-indicator"))).getText();
Assert.assertEquals(expectedName, actualName);
xpath:
String expectedName = "Employee Name";
String actualName = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#class='dx-datagrid-text-content dx-text-content-alignment-left dx-header-filter-indicator']"))).getText();
Assert.assertEquals(expectedName, actualName);
Tooltip imageNot able to handle tooltip with getAttribute and getText in selenium java.
Below is the code
HTML :
<span class="exclude-syndicated-hint hint--top" data-hint="Programs like
"The Today Show" are often syndicated across major networks and
play on a variety of channels. Checking this box will only give you a
single copy of the program.">
<i class="syndicated-hint-icon fa fa-info-circle"></i>
</span>
JAVA :
#FindBy(xpath = "//i[#class='syndicated-hint-icon fa fa-info-circle']")
public WebElement tooltip;
public String settooltip()
{
Actions a = new Actions(driver);
a.moveToElement(tooltip).perform();
String actualTooltip = tooltip.getAttribute("data-hint");
}
// Create action class object
Actions builder=new Actions(driver);
// find the tooltip xpath
WebElement _tooltip=driver.findElement(By.xpath("//span[#class='exclude-syndicated-hint hint--top']));
// Mouse hover to that text message
builder.moveToElement(_tooltip).perform();
// Extract text from tooltip
String tooltip_msg=_tooltip.getAttribute("data-hint");
// Print the tooltip message just for our refrences
System.out.println("Tooltip message is "+tooltip_msg);
Try this:-
You need to call perform() on Actions class methods.
First we need to create new action builder instance by passing the webdriver instance.
Read more about moveToElement
For more information about mouse hover actions read this
Actions toolAct = new Actions(driver);
toolAct.moveToElement(element).build().perform();
WebElement toolTipElement = driver.findElement(By.xpath("//span[#class='exclude-syndicated-hint hint--top']));
String toolTipText = toolTipElement.getText();
System.out.println("tooltip :- "+toolTipText);
Ok, in parts:
#FindBy(xpath = "//i[#class='syndicated-hint-icon fa fa-info-circle']")
public WebElement tooltip;
Is finding the
<i class="syndicated-hint-icon fa fa-info-circle"></i>
Which doesn't have the attribute "data-hint".
But you still try to get the attribute from it.
String actualTooltip = tooltip.getAttribute("data-hint");
First things first, if you want to get this value, you don't even need to hover it, hover the element itself and get the attribute value is not really "testing (not the right word to use here)" the tooltip thing.
But thinking from the point that you still want to hover it, you can do like this:
#FindBy(xpath = "LOCATOR FOR THE <span> AND NOT THE <i>")
public WebElement tooltip;
public String getTooltipMessage() {
Actions action = new Actions(driver);
action.moveToElement(tooltip).build().perform();
String actualTooltip = tooltip.getAttribute("data-hint");
}
case you just want to get the message
#FindBy(xpath = "LOCATOR FOR THE <span> AND NOT THE <i>")
public WebElement tooltip;
public String getTooltipMessage() {
String actualTooltip = tooltip.getAttribute("data-hint");
}
Try below css selector
#FindBy(css = "span[class='exclude-syndicated-hint.hint--top']");
or
#FindBy(css = "i[class='syndicated-hint-icon.fa.fa-info-circle']");
I'm attempting to scrape the text 64076 next to Item model number: on this page using the following XPath expression:
//*[contains (#id,'productDetails')]//tr[contains(.,'Item model number')]/td|//*[contains (#id,'detail')]//descendant::li[contains(.,'Item model number')]/text() // I'm focusing mainly on second half of expression..
However, although this matches the expected text (64076) in Firebug it is not found when using Selenium WebDriver (Java).
When I change the XPath to:
//*[contains (#id,'productDetails')]//tr[contains(.,'Item model number')]/td|//*[contains (#id,'detail')]//descendant::li[contains(.,'Item model number')]
It works however it also scrapes the text Item model number: which I do not want (I know I could parse the result using regex but I'm trying to understand why my XPath is not working since I am clearly matching the actual text/number via text(), not the bold text)
Thanks
It's because text() in XPath means to find TextNode, but for Selenium only support to find and return ElementNode. Also Attribute Node not supported by Selenium, but support in XPath.
You have to find the parent(which is an ElementNode) of the TextNode, then use regex or split to extract you wanted sting.
String xpath = "//ul/li[b[text()='Item model number:']][contains(. , '64076')]"
driver.findElement(By.xpath(xpath)).getText().split()[1]
This is a common problem in selenium since it only supports XPath 1.0 which does not include text(). The usual approach is to get the node and call getText().
Here is a nicely wrapped function to get the text without any text from the children:
public static String geNodeText(WebElement element) {
String text = element.getText();
for (WebElement child : element.findElements(By.xpath("./*"))) {
text = text.replaceFirst(child.getText(), "");
}
return text;
}
Sure enough, you can use string functions or regex to extract the string in question as well. But this probably requires you to write custom extraction logic for each case.
You cannot use Selenium to get it directly because it is TextNode.
You may use JavaScript to check the text node and get it.
WebElement itemModelRootNode = driver.findElement(by.xpath("//*[contains (#id,'productDetails')]//tr[contains(.,'Item model number')]/td|//*[contains (#id,'detail')]//descendant::li[contains(.,'Item model number')]");
String script = "var t = ''; arguments[0].childNodes.forEach((node)=>{ if(node.nodeType==Node.TEXT_NODE && node.textContent.trim().length > 0) { t = node.textContent.trim(); } }); return t;"
String text = ((JavascriptExecutor)driver).executeScript(script, itemModelRootNode);
More in #Bauban Answer. Selenium doesn't allow to locate an element using text node. You can try with evaluate() method of JavaScript and evaluate your xpath using JavascriptExecutor
This is your xpath :
//div[#class='content']//li[contains(.,'Item model number:')]/text()
And this is how you can evaluate:
JavascriptExecutor js = (JavascriptExecutor)driver;
Object message = js.executeScript("var value = document.evaluate(\"//div[#class='content']//li[contains(.,'Item model number:')]/text()\",document, null, XPathResult.STRING_TYPE, null ); return value.stringValue;");
System.out.println(message.toString().trim());
You can refer this link to get more details about evaluate function.
As per the url you have shared to extract the text 64076 next to Item model number: on this page as it is a Text Node you need to use WebDriverWait for the desired element to be visible and you can use the following solution:
Code Block:
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class q52359631_textExtract {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.amazon.com/dp/B000TW3B9G/?tag=stackoverflow17-20");
WebElement myElement = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//td[#class='bucket']//li/b[contains(.,'Item model number:')]/..")));
String myText = (String)((JavascriptExecutor)driver).executeScript("return arguments[0].lastChild.textContent;", myElement);
System.out.println(myText);
}
}
Console Output:
64076
Try for Item model number: 64076 for the test URL
var xpathExp =
"//h2[.='Product details']//parent::td//div[#class='content']/ul/li/b[contains(text(),'Item')]/parent::li/text()";
var ele = $x(xpathExp);
console.dir( ele ); // Array(1)
console.log( ele[0] ); //" 64076"
Test XML XPath online:
<ul>
<li>
<b>Item model number:</b> 64076
</li>
</ul>
XML Tree View codebeautify //ul/li/b[contains(text(),'Item')]/parent::li/text()
ul ..
li 64076 ..
b Item model number:
html as javascript object
outerHTML:"<li><b>Item model number:</b> 64076</li>"
outerText:"Item model number: 64076"
tagName:"LI"
textContent:"Item model number: 64076"
lastChild:text
data: 64076"
nodeValue: 64076"
textContent: 64076"
wholeText: 64076"
lastElementChild:b
Html
<div class="rc-anchor-light">
<div id="accessible-status" class="rc-anchor-aria-status" aria-hidden="true">requires verification.</div>
</div>
My expected
Extract the text from inside the div "requires verification."
tried below locator, but i'm not getting my expected.
unique id so i tired with id getting empty result
String accessText = driver.findElement(By.id("accessible-status")).getText();
using class name getting empty result
String accessText = driver.findElement(By.className("rc-anchor-aria-status")).getText();
Please suggest me how to get the value.
Text content of target div node might be generated dynamically. Try to implement ExplicitWait for element with any text:
WebDriverWait wait = new WebDriverWait(webDriver, 10);
WebElement divNode = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#id='accessible-status' and normalize-space()]"));
String accessText = divNode.getText();
If element has text from the very beggining, but it is just hidden, getText() will not return you text. In this case you may try
String accessText = driver.findElement(By.id("accessible-status")).getAttribute("textContent");
As per the HTML you have shared to extract the text requires verification. from the div you need to use a Locator Strategy to identify the WebElement uniquely and induce WebDriverWait with ExpectedConditions set as visibilityOfElementLocated(By locator) for the WebElement to be visible in the HTML DOM and finally use getAttribute() method to to extract the text. You can use the following line of code :
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#class='rc-anchor-light']/div[#class='rc-anchor-aria-status' and #id='accessible-status']"))).getAttribute("innerHTML"));