Use Selenium Java to get string text from HTML - java

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.

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>

Selenium says invalid xpath locator

I am trying to get value of HREF attribute but always it says incorrect Xpath.
Html Code :
I am trying code :
WebElement Link = driver.findElement(By.xpath("//table[contains(#class,'display')]/thead/tbody/tr/td/a"));
System.out.println(Link.getAttribute("href"));
I tried many xpath but none of them worked.
This should work:
WebElement Link = driver.findElement(By.xpath("//table[contains(#class,'display')]/tbody/tr/td/a"));
Explanation: tbody is not nested in thead.
Note that a path expression like this can return a set of several nodes, in document order. The findElement method only returns the first result node. So: if the a element you are looking for is no longer the first one in this table, the path expression breaks.
If the the href is unique, something like this would be less error-prone:
WebElement Link = driver.findElement(By.xpath("//table[contains(#class,'display')]//a[#href='/admin/client/product_overrides/edit/242625']"));

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

NoSuchElementException when using By.Xpath

Edit :
The element was inside an iframe, this is how it finally worked:
WebDriverWait wait = new WebDriverWait(_driver, 60);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By
.xpath("//*[#class='IFrameID']")));
WebElement element_t = _driver.findElement(
By.xpath("//*[#myattribute='mytest']"));
Edit :
My problem seems to be the structure of the page. i tried different things, and i only was able to get the body by id, ever other element i tried to get by id or any other attribute couldnt be found...
I am trying to get an element by using the By.xpath method, the xpath itself works just fine when used in firebug/firepath, but when used in the java application i am getting an Exception:
org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":".//*[#myattribute='mytest']"}
The attribute i am trying to access is not a standard html one, but generated from a framework so the field looks like this :
<input id="F_19" class="FIELDInputEdit" type="text" style=" width:100%;" maxlength="40" myattribute="mytest" name="CC">
The javacode itself looks like this :
WebElement element_t = _driver.findElement(
By.xpath(".//*[#myattribute='mytest']"));
Since the only known attribute is this one, i have no ohter way to access the input field.
I am using Firefox 17.0.11
good practice (imho) before using xpath in webdriver test it using selenium ide (http://docs.seleniumhq.org/download/)
Error might be because of «.» before «//». Try to remove it.
Read this: http://www.w3schools.com/xpath/xpath_syntax.asp
.//*[#myattribute='mytest']
«.» = Selects the current node
«//» = Selects nodes in the document from the current node that match the selection no matter where they are
«*» = Matches any element node
«[#myattribute='mytest']» ( = [#myattribute = \"mytest\"]) = Node, that contains attribute "myattribute", which value is "mytest"
Now, _driver.findElement(By.xpath("//*[#myattribute='mytest']")) = search whole page for first node with attribute «myattribute» with value «mytest»
_driver.findElement(By.xpath("//input[#myattribute='mytest']"))
= search whole page for first input with «myattribute» = «mytest»
_driver.findElement(By.xpath("//input[#myattribute='mytest']")).then(By.path("./*[#comeAtr]")) = in input with «myattribute» = «mytest» find any node with atribute = «
Have you tried to use CSS selectors instead?
By.cssSelector("input[myattribute=\"mytest\"]")
The element was inside an iframe, this is how it finally worked:
WebDriverWait wait = new WebDriverWait(_driver, 60);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By
.xpath("//*[#class='IFrameID']")));
WebElement element_t = _driver.findElement(
By.xpath("//*[#myattribute='mytest']"));

Selenium WebDriver Finding Element by Partial Class Name

In the frame I'm working with, I have the following element:
<div class="x-grid3-cell-inner x-grid3-col-expRepCol"> New session from client IP 192.168.5.3 (ST=/CC=/C=) at VIP 192.168.5.2 Listener /Common/Tomcat (Reputation=Unknown)</div>
As well as many other similar elements. I am trying to locate this element by partial name text and click it with the following code:
String expectedText = "New session from client IP";
driver.findElement(By.className("div[class*='"+expectedText+"']")).click();
And I have also tried with cssSelector:
String expectedText = "New session from client IP";
driver.findElement(By.cssSelector("div[class*='"+expectedText+"']")).click();
But WebDriver keeps throwing an exception stating it's unable to locate that element. Any suggestions as to what could be the problem?
<div class="dd algo algo-sr Sr" data-937="5d1abd07c5a33">
<div class="dd algo algo-sr fst Sr" data-0ab="5d1abd837d907">
Above 2 are the HTML elements in yahoo search results. So if we wanna get these elements using partial class name with selenium python, here is the solution.
driver.find_element_by_css_selector("div[class^='dd algo algo-sr']")
In the same way we can get any elements with partial match on any attribute values like class name, id etc.
find elements with css selector partial match on attribute values
By.className is looking for a class with the name entered.
By.cssSelector is looking for a match for the selector you entered.
What you're attempting is to match the text of the div against class, which won't work.
You can try something like this:
driver.findElement(By.xpath("//div[contains(text(),'"+expectedText+"')]")).click();
I believe this will work:
driver.findElement(By.className("x-grid3-cell-inner x-grid3-col-expRepCol").click();

Categories

Resources