Selenium getText - java

I want to getText() using By.id or By.cssSelector.
I managed to solve my problem by doing getAttribute("value"), but I don't understand why getText() doesn't work like I expect it, and I might need it so all help is appreciated.
Here is the Java code:
WebDriverWait wait = new WebDriverWait(driver, 10);
Boolean elementIsPresent = wait.until(ExpectedConditions.textToBePresentInElementValue(By.cssSelector("#general_service_name"),"[reg] general_service_name")); // true
//WebElement general_service_name = driver.findElement(By.cssSelector("#general_service_name"));
WebElement general_service_name = driver.findElement(By.id("general_service_name"));
// Display check
Boolean isDisplayed;
if(general_service_name.isDisplayed()) isDisplayed = new Boolean(true); else isDisplayed = false; //true
String text_empty = general_service_name.getText(); //""
String text_with_value = driver.findElement(By.id("general_service_name")).getAttribute("value"); //"[reg] general_service_name"
And HTML:
<input id="general_service_name" type="text" value="[reg] title" name="general_service_name" style="float:left;"/>

http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html#getText()
getText() delivers the innerText of a WebElement.
Your input field does not have any inner Text. The text is found inside your value-attribute, hence accessing it via getAttribute("value") is the correct way to do it.

Java
ele.getAttribute("innerHTML");
This could get the text already in the background and not displayed on the page yet.

Simple answer - it's designed this way. getText() parses the content of the tag (i.e. its innerText), which is obviously empty for inputs.

You may use this if you want to search for a given text on a WebElement. Pass it directly or through a string:
String textoToSearch = "Text inside Webelement";
driver.findElement(By.id("someID).getText().contains("textToSearch");

getText()
getText() returns the visible text of this element.
java.lang.String getText()
Get the visible (i.e. not hidden by CSS) text of this element, including sub-elements.
Returns:
The visible text of this element.
As per the HTML of the element:
<input id="general_service_name" type="text" value="[reg] title" name="general_service_name" style="float:left;"/>
The WebElement doesn't have a visible text but the value attribute have the value set as [reg] title.
So to extract the value of the value attribute i.e. [reg] title you can use either of the following Locator Strategies:
Using cssSelector:
System.out.println(wd.findElement(By.cssSelector("input#general_service_name[name='general_service_name']")).getAttribute("value"));
Using xpath:
System.out.println(wd.findElement(By.xpath("//input[#id='general_service_name' and #name='general_service_name']")).getAttribute("value"));
Ideally, you need to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:
Using cssSelector and getText():
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input#general_service_name[name='general_service_name']"))).getAttribute("value"));
Using xpath and getAttribute("innerHTML"):
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[#id='general_service_name' and #name='general_service_name']"))).getAttribute("value"));

Related

How to extract text from td node using Selenium and Java

I need to get the text of a td element with selenium. I have problem with extract text, I just receive null. I tried used list, getText() and so on. The HTML code is on the picture and element looks like you can see on the picture.
getDriver().findElement(By.xpath("//*[#id=\"standortTable\"]/tbody/tr/td[2]")).isDisplayed();
String test = getDriver().findElement(By.xpath("//*[#id=\"standortTable\"]/tbody/tr/td[2]")).getText();
System.out.println(test);
But I receive NULL, just "".
I guess you are missing a wait I.e. you trying to read the element text content before it is completely rendered.
Try this:
WebDriverWait wait = new WebDriverWait(getDriver(), 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//table[#id='standortTable']//td[#aria-colindex='2']")));
String test = getDriver().findElement(By.xpath("//table[#id='standortTable']//td[#aria-colindex='2']")).getText();
System.out.println(test);
The element is an Angular element, so to extract the text Teststandort1 you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:
Using xpath and getText():
System.out.println(new WebDriverWait(getDriver(), 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//table[#id='standortTable']//tbody//tr[#class='ng-star-inserted']//td[#aria-colindex='2']"))).getText());
Using cssSelector and getAttribute("innerHTML"):
System.out.println(new WebDriverWait(getDriver(), 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("table#standortTable tbody tr.ng-star-inserted td[aria-colindex='2']"))).getAttribute("innerHTML"));

How to Assert a Text In Regional Language like Hindi in Selenium

I want to validate a text but its in Hindi in the website i am working on .
The code goes this way
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.textToBePresentInElementLocated(
By.xpath("/html/body/nav[1]/div/ul/div/div/li[2]/form/input[4]"),
"हिंदी"));
System.out.println("Language changed to "+ landingpage.getHindiLanguage().getText());
And The Output I Get is
Expected condition failed: waiting for text ('?????') to be present in element found by By.xpath:
How shall i approach this?
From your xpath assuming you are trying to getText from a input tag
Input tag stores the value in value attribute so you should get the value from the attribute instead of using getText() use
webelement.getAttribute("value") this will return values stored in input field
getText() will works only for HTML element which store values in node.
Like p tag as shown below
<p>PARAGRAPH</p>

Webdriver: Locate typefield via placeholder text then text via sendkey("test text") into the typefield

I have been trying to send a text to a text field that has the changing element id=PolarisTextField83 each time a log into a page (PolarisTextField## keeps changing its value like id=PolarisTextField45) as I have found that the id element is dynamic and the only static and unique part of the HTML is the placeholder example text which is placeholder="e.g. Shirts".
Therefore, I wonder if there is a way of locating placeholder="e.g. Shirts" then sending text to its respective type field (PolarisTextField##)?
I have tried to use
driver.findElementsByTagName("e.g. Shirts").sendKeys("test text");
but came to the understanding that I cannot follow .sendKeys() after findElementsByTagName.
I am new to both java and selenium and would appreciate any help and/or guidance!!
You can find the element by placeholder value using XPath
driver.findElement(By.xpath("//*[#placeholder='e.g. Shirts']")).sendKeys("test text");
Try below xpath to deal with dynamic web element.
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.findElement(By.xpath("//*[starts-with(#id,'PolarisTextField')]")).sendKeys("Test");
To send a character sequence within the element you can use either of the following Locator Strategies:
Using css_selector, id and placeholder attributes:
driver.findElement(By.cssSelector("[id^='PolarisTextField'][placeholder$='Shirts']")).sendKeys("test text");
Using xpath, id and placeholder attributes:
driver.findElement(By.xpath("//*[starts-with(#id, 'Shirts') and contains(#placeholder, 'Shirts')]")).sendKeys("test text");
Ideally, to send a character sequence within the element you have to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("[id^='PolarisTextField'][placeholder$='Shirts']"))).sendKeys("test text");
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[starts-with(#id, 'Shirts') and contains(#placeholder, 'Shirts')]"))).sendKeys("test text");

Use Selenium Java to get string text from HTML

I want to get Selenium with Chromedriver to recognize and import a line of html text into a Webelement variable.
Given this HTML:
<li id="password_rules">
<strong>Password Rules</strong>
<p>The database password rules conform with...:</p>
<ul>
<li>The password can not be the same as the user id.</li>
<li>Password length must be between 8 and 25 characters.</li>
</ul>
</li>
I want to grab the text in the last list element ("Password length must be between 8 and 25 characters.").
This is the java code I'm attempting to use:
WebElement passwordCriteria = driver.findElement(By.xpath("//*[#id = 'password_rules']//*[contains(text(), 'Password length must be between ')]"));
String lineText = passwordCriteria.getText();
When that Java executes, it returns an error saying the element cannot be found:
Exception in thread "main"
org.openqa.selenium.InvalidSelectorException: invalid selector: Unable
to locate an element with the xpath expression //[contains((text(),
'Password length must be between ')] because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string
'//[contains((text(), 'Password length must be between ')]' is not a
valid XPath expression.
Any insight is much appreciated.
If you are grabbing a WebElement by it's id, then you don't need your extra specific xPath. id is supposed to be unique by convention. If you have other html elements with the same id, consider changing them to a class.
You should be able to grab the element like this:
WebElement passwordCriteria = driver.findElement(By.id("password_rules"));
If you're committed to finding the element by the id containing some text then the way you should do it is as follows:
WebElement passwordCriteria = driver.findElement(By.xpath("//*[contains((text(),'Password length must be between')]"));
Also, sometimes Selenium will complain if elements are not visible on the page when you try and reference them. Sometimes you need to wait, other times you need to perform some other action to make the text visible before referencing it, like hovering the mouse over a dropdown, etc.
For example
Suppose the html you pasted here is an error message. This error message does not start out as being 'visible', but instead it is shown after the user types their password in incorrectly. In such an instance, Selenium won't let you reference the text from an element inside this div, since it's not currently view-able. Instead, what you would have to do is use Selenium to input the incorrect password in the fields, wait for the error message to be displayed, and then finally reference the WebElement, only after it is able to be seen.
EDIT:
I misread OP's intention. The element that OP is trying to reference is NOT the element with the id, but rather a child of that element. Instead of rewriting my answer, I will point out that #Grasshopper answer has both css and xPath solutions.
You can try these locators if the concerned li is always the last child.
Css - "li[id='password_rules'] > ul > li:last-child"
xpath - "//li[#id='password_rules']/ul/li[last()]"
As per your question as the desired text is within Password Rules you have to induce WebDriverWait with ExpectedConditions as textToBePresentInElementLocated and then retrieve the text as follows :
new WebDriverWait(driver, 20).until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//li[#id='password_rules']//ul//li"), "Password length"));
String lineText = driver.findElement(By.xpath("//li[#id='password_rules']//ul//li[contains(.,'Password length')]")).getAttribute("innerHTML");
Thank you for the help everyone. I finally got it using the following:
new WebDriverWait(driver, 20).until(ExpectedConditions.textToBePresentInElementLocated(By.xpath("//li[#id = 'password_rules']"), "Password length must be between "));
WebElement passwordCriteria = driver.findElement(By.xpath("//li[#id = 'password_rules']/ul/li[2]);
String lineText = passwordCriteria.getText();
Your original example had // which should only be used at the beginning of an xpath.

Java Selenium, how to get linkText (anchor) from link WebElement

I have a WebElement containing link found by url. I can extract url by:
element.getAttribute("href");
But the question is: how to extract it's anchor, I'm trying like this:
webElement.getAttribute("linkText");
It gives me null value. I'm 100% sure this link has an anchor. Is there any way to get anchor ? It's more complicated, but example simplified code could look like this:
WebDriver driver = new FirefoxDriver();
driver.get("http://stackoverflow.com/questions/tagged/java");
WebElement link = driver.findElement(By.linkText("Bicycles"));
System.out.println(link.getAttribute("href")); // shows http://bicycles.stackexchange.com/
System.out.println(link.getAttribute("linkText")); // shows null
Try this:
System.out.println(link.getText());
If getText() returns an empty String, try the innerHTML attribute:
String text = element.getAttribute("innerHTML")
By "Anchor" I think you mean the text of the link? If so, then you can use .getText() since an <a> is a block level element.
link.getText();
Here you can store your id text:
String text = driver.findElement(By.id("Text")).getText();
System.out.println(text);

Categories

Resources