Select the String value of an element using xpath , in Selenium Java - java

I am completely new to selenium. I am using Selenium and java.The following is my resulting screen value. I want to select the double quoted data(Test) from this screen, and i want to replace it to a different value.
"value": "Test",**
"createDateTime": "2016-08-23T15:37:06+0100",
"channel": "POST",
Note: the whole data is under a div class =ace_gutter, the parent div class is "aceEditor".
After a long struggle i found the following xpath for that row which i want to get the value from.
HTML code:
#11
Xpath:
It is this
[#id='aceEditor']/div[1]/div[1]/div[11].
myCode:
String value= driver1.findElement(By.xpath("//*[#id='aceEditor']/div[1]/div[1]/div[11]")).getAttribute("innerHTML") ;
It is giving 11, instead of the actual text("value": "Test",)from the screen. Could any one Please help me with the code. I have searched enough i am not finding any solution.

To replace the value in the HTML page, you will have to use the executeScript method.
String replace_text = "Text to be replaced";
js = ((JavascriptExecutor) driver)
js.executeScript("return document.getElementById('<id of the element>').innerHTML='" + replace_text + "';");

Related

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>

How to get the value of label text in selenium webdriver

I'm trying to get the value of a permission key in Selenium web-driver(java), but I couldn't able to identify the element. Can anyone please help me to identify the element and get the value "4BF12-50763-166E0".
There are 9 span class with same name and it's quite hard to identify the same.
The web page part look like as below and i want to take each of the below elements value like version, status etc. All are present in the span class as shown in the below pic.
Any suggestions will be of great help.
Version 1.2
Status Enabled
Days left 373
Permission KEY 4BF12-50763-166E0
Permission Serial Number 99678905096711
Subscription End Date 2020-08-31
The sample of the HTML is attached.
I have tried this, but it is selecting "Permission KEY" only.
WebElement details = driver.findElement(By.xpath("//b[text()='Permission KEY']"));
String title = details.getAttribute("title");
String label = details.getText();
System.out.println("Title is " +title);
System.out.println("Label is" +label);
You can find your desired text in this case "Permission Key" go the ancestor element and go to the second span that contains the value.
XPath:
String xpath = "//b[text()='Permission Key']/ancestor::dd/span[2]";
WebElement spanElement = driver.findElement(By.xpath(xpath));
spanElement.getText(); // Will give you '4BF12-50763-166E0'
IMPORTANT NOTE: You can change the 'Permission Key' to any other value like for example 'Version' and IF they follow the same pattern, it will work for all, example:
String xpath = "//b[text()='Version']/ancestor::dd/span[2]";
WebElement spanElement = driver.findElement(By.xpath(xpath));
spanElement.getText(); // Will give you '1.2'
You can use preceding-sibling strategy in your xpath, try this bellow :
WebElement key = driver.findElement(By.xpath("//span[#class='pull-right property-value' and ./preceding-sibling::span/b[contains(text(),'Permission KEY')]]"));
System.out.println("Permission KEY : " +key.getText());
Make sure this is the correct class name : #class='pull-right property-value', because i see from your image.

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.

how to get a text string from

I am creating an automatic test for some webs and I'm using WebDriver, TestNG and code that is written in Java. On the page is shown register of categories, in parentheses is number of auctions and i need to get this number as variable, but i don't know, how.
I use the following code:
WebElement number1_1_vse = (driver.findElement(By.linkText("Vše")));
String text_vse1_1 = number1_1_vse.getText();
but output is only: "Vše" without (number of auctions)
link to the website
screenshot -> image with the number
can anyone advise me please?
With linktext you are finding the nested a which text is Vše only. You need to find the li containing the text Vše (949)
Use the following css selector to identify the element
By bycss =By.cssSelector(".list.list-categories>li:first-child");
WebElement number1_1_vse = driver.findElement(bycss );
String text_vse1_1 = number1_1_vse.getText();
WebElement parent = number1_1_vse.findElement(By.xpath(".."));
// which will give you access to <li>
List<WebElement> childs = parent.findElements(By.xpath(".//*"));
// childs.get(1) has the result.
Please try to get the xpath value and then try to search it with below mentioned syntax :
findelementbyxpath("//*[#id="post-form"]/h2")
To get xpath value of and element : right click --> inspect element --> right click copy 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