How to get the text from element in Selenium - selenium

I am trying to fetch the text ($315.50) from:
<td id="balance" class="ng-binding">$315.50</td>
I am not succeeding though, I have tried:
#FindBy(how = How.CSS, using = "#balance")
private WebElement balance;
and
#FindBy(how = How.ID, using = "#balance")
private WebElement balance;
With these selectors I than do:
System.out.println("Balance" + balance)
as result I get
Balance[[ChromeDriver: chrome on WINDOWS (4ccbccdb5b54de0526e0ec68db88a48c)] -> css selector: #balance]
Or if try to do something else with it, I get errors saying that the methods receives an empty string.
For other elements in my test framework I can do manage to fetch the text from elements. The general setup does not seem to be the problem. Anyone an idea what I am doing wrong in this specific example?

Considering the HTML:
<td id="balance" class="ng-binding">$315.50</td>
To identify the element you can use either of the following locator strategies:
Using id:
#FindBy(how = How.ID, using = "balance")
private WebElement balance;
Using cssSelector:
#FindBy(how = How.CSS, using = "td#balance")
private WebElement balance;
Using xpath:
#FindBy(how = How.XPATH, using = "//td[#id='balance']")
private WebElement balance;
To print the text:
Using getText():
System.out.println(balance.getText())
Using getAttribute("innerHTML"):
System.out.println(balance.getAttribute("innerHTML"))
Using getAttribute("innerText"):
System.out.println(balance.getAttribute("innerText"))
Using getAttribute("textContent"):
System.out.println(balance.getAttribute("textContent"))

Related

How to find a webelement that has 'checked' attribute in list of child WebElements through Selenium using Katalon Studio

I have radio buttons that when either radio button is selected, it gets a checked attribute.
This is how the HTML looks:
My implementation of getting the descendant that has a checked attribute:
public TestObject getCheckedTestObjectFromParent(String parentID){
WebDriver driver = DriverFactory.getWebDriver()
WebElement parentWebElement = driver.findElement(By.id(parentID))
List<WebElement> children = parentWebElement.findElements(By.xpath(".//*"))
println(children.size())
for(int i = 0; i < children.size(); i++){
TestObject childTestObject = getTestObjectFromWebElement(children[i])
if(WebUI.verifyElementHasAttribute(childTestObject, 'checked', 10, FailureHandling.OPTIONAL)){
return childTestObject
}
}
}
This is the helper method that I use for converting a WebElement to a TestObject :
public TestObject getTestObjectFromWebElement(WebElement element) {
TestObject object = new TestObject()
object.addProperty("xpath", ConditionType.CONTAINS, getXPathFromElement(element))
return object
}
Helper for getting xpath from WebElement :
protected String getXPathFromElement(WebElement element) {
String elementDescription = element.toString();
return elementDescription.substring(elementDescription.lastIndexOf("-> xpath: ") + 10, elementDescription.lastIndexOf("]"));
}
Am I missing something here or is there something wrong with the WebElement -> TestObject conversion? Also is this possible using only TestObject or only WebElement? If I could get child TestObjects containing certain attributes from a parent TestObject then I wouldn't need to make a mess using WebElements.
Edit
Another image of the HTML, this time with the first radio button checked. As you can see the second radio button no longer has the 'checked' attribute.
To retrieve the WebElement that is currently checked you can use either of the following Locator Strategies:
cssSelector:
WebElement elem = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.a-toggle.a-toggle--anycase#config-src-laserunits div[id^='config-src-laserunits-']>input.a-toggle__radio[checked]")));
xpath:
WebElement elem = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#class='a-toggle a-toggle--anycase' and #id='config-src-laserunits']//div[starts-with(#id, 'config-src-laserunits-')]/input[#class='a-toggle__radio' and #checked]")));
I was able to fix this by changing (".//*") to (".//*[#checked='checked']")
parentWebElement.findElement(By.xpath(".//*[#checked='checked']")
will find the element that has the attribute checked = 'checked'
Notice that a list is no longer needed as there can only be 1 checked radio button at a time.
Implementation
public TestObject getCheckedTestObjectFromParent(String parentID){
WebDriver driver = DriverFactory.getWebDriver()
WebElement parentWebElement = driver.findElement(By.id(parentID))
//there is only 1 checked child at a time, so there is no need for a list
WebElement checkedChild = parentWebElement.findElement(By.xpath(".//*[#checked='checked']"))
//convert the WebElement to a TestObject and return
return getTestObjectFromWebElement(checkedChild)
}
Try this Xpath
"//input[#id='config-src-laserunits-wavnmradio' and #checked='checked']"
Example:
List<WebElement> children = driver.findElements(By.xpath("//input[#id='config-src-laserunits-wavnmradio' and #checked='checked']"))
It should return size 1
EDIT
List<WebElement> children = driver.findElements(By.xpath("//input[#id='config-src-laserunits-wavnmradio']"));
for (int i=0;i<children.size();i++)
{
if(children.get(i).getAttribute("checked")!=null)
{
System.out.println("radio button is checked");
}
}

Selenium- How to find a locator for Web Element?

I am working on finding a solution how to generate a Selenium locator to an element:
<a name="page" data-role="button" data-mini="true" data-inline="true" href="https://blablabla/bla/bla/bla/?formTemplatesList_start=120" data-aid="paginator-link-last">Last</a>
My ideas:
#FindBy(how = How.PARTIAL_LINK_TEXT, using = "paginator-link-last")
public WebElement lastTemplateButton;
#FindBy(how = How.XPATH, using = "//a[#data-aid='paginator-link-last']")
public WebElement lastTemplateButton;
It does not work... I have no other ideas.
I receive NULL POINTER EXCEPTION when I run:
public void selectTemplateToEdit() {
CustomWaitImpl.waitForElementDisplayed(editEvalTemplateLocators.getLastTemplateButton());
editEvalTemplateLocators.getLastTemplateButton().click();
}
can you try the following:
#FindBy(how = How.XPATH, using = "//a[#data-aid = 'paginator-link-last']")
Public WebElement lastTemplateButton;
OR
#FindBy(how = How.XPATH, using = "//a[#data-aid = 'paginator-link-last' and contains(text(), Last]")
Public WebElement lastTemplateButton;
If any of it works, I would recommend just removing the, how = How.XPATH and simply just doing the following code below as a reference:
#FindBy(using = "//a[#data-aid = 'paginator-link-last' and contains(text(), Last]")
Try with this xpath and also use webDrver wait
//a[contains(text(),'Last')]

selenium span link li not working

I am new to selenium. I am practicing to write a test case on http://www.countdown.tfl.gov.uk. Below are the steps I followed:
a) I opened the browser to selenium Web Driver
b) Found the search text Box and enter H32 and clicked on search button to selenium.
Till this part it works fine.
Now on the page I am actually getting two records on the left side of the page under the search. I am actually trying to click on the first one i.e. "Towards Southall,Townhall" link. Nothing is happening.
Below is my code:
public class CountdownTest {
#Test
public void tflpageOpen(){
WebDriver driver = openWebDriver();
searchforBus(driver,"H32");
selectrouteDirection(driver)
}
//open the countdowntfl page
private WebDriver openWebDriver(){
WebDriver driver = WebDriverFactory.getWebDriver("FireFox");
driver.get("http://www.countdown.tfl.gov.uk");
return driver;
}
private void searchforBus(WebDriver driver,String search){
WebElement searchBox = driver.findElement(By.xpath("//input[#id='initialSearchField']"));
searchBox.sendKeys(search);
WebElement searchButton = driver.findElement(By.xpath("//button[#id='ext-gen35']"));
searchButton.click();
}
private void selectrouteDirection(WebDriver driver){
WebElement towardssouthallLink= driver.findElement(By.xpath("//span[#id='ext-gen165']']"));
((WebElement) towardssouthallLink).click();
}
}
Please help me.
Thanks.
Since you are getting NoSuchElement Exception now, you may try the following code with the usage of WebDriver explicit wait.
WebDriverWait wait = new WebDriverWait(driver, 15);
WebElement towardssouthallLink = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("(//*[#id='route-search']//li/span)[1]")));
towardssouthallLink.click();
Or WebDriver implicit wait
WebDriver driver = WebDriverFactory.getWebDriver("FireFox");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://www.countdown.tfl.gov.uk");
Tips:
The search results need some time to be retrieved, so please use Explicit wait or Implicit wait.
Don't use locators like span[#id='ext-gen165'], they are ExtJs auto generated.
In this case, css selector can also be used: #route-search li:nth-of-type(1) > span
You aren't calling selectrouteDirection.
You probably want:
#Test
public void tflpageOpen(){
WebDriver driver = openWebDriver();
searchforBus(driver,"H32");
selectrouteDirection(driver);
}
You also don't need to cast here:
((WebElement) towardssouthallLink).click();
It's already a WebElement anyway.
I found that id for those links are dynamically generated. ids are of the form 'ext-genXXX' where XXX is number which is dynamically generated hence varies each time.
Actually, you should try with linkText:
For 'Towards Southall, Town Hall'
driver.findElement(By.linkText("Towards Southall, Town Hall")).click
For 'Towards Hounslow, Bus Station'
driver.findElement(By.linkText("Towards Hounslow, Bus Station")).click
Here is a logic:
Get all elements which have id starts with 'ext-gen' & iterate over it & click on link with matching text. Following is Ruby code(sorry, I don't know Java well):
links = driver.find_elements(:xpath, "//span[starts-with(#id, 'ext-gen')]")
links.each do |link|
if link.text == "Towards Southall, Town Hall"
link.click
break
end
end

Webdriver returns error for textarea.sendKeys(text)

I am using Webdriver 2.25.0 and Firefox 14
I have the following textarea:
<textarea id="source-text" placeholder="Start typing your text" style="resize: none; overflow: hidden;"></textarea>
I am identifying this text area in my HomePage object like this:
#FindBy(how = How.CSS, using = "div.myclass textarea")
public WebElement columnLeftTextarea;
What i want to do is simply type some text inside this textarea, by using the following code
homePage.columnLeftTextarea.sendKeys("some text");
This is returning the following error:
Type mismatch Can't assign non-array value to an array
The textarea is correctly defined as when i run
homePage.columnLeftTextarea.getAttribute("placeholder")
i get the correct text
I even tried to do start the browser by setting the capabilities to tnable native events:
FirefoxProfile ffProfile = new FirefoxProfile(new File(generalPropertiesTestObject.getFirefox_profile_template_location()));
ffProfile.setEnableNativeEvents(true);
FirefoxDriver ffd = new FirefoxDriver(ffProfile);
capabilities = ffd.getCapabilities();
But still i am getting the same error. Does anyone have any idea about it?
Try firstly focusing into textarea. I did it using the following code:
driver.findElement(By.id("source-text")).clear();
driver.findElement(By.id("source-text")).sendKeys("some text");
and it seems to work just fine.
You need change this code:
#FindBy(how = How.CSS, using = "div.myclass textarea")
public WebElement columnLeftTextarea;
on this:
#FindBy(how = How.ID, using = "source-text")
public WebElement columnLeftTextarea;
Firstly, it works more faster, because search by ID works more faster than search by CSS.
Secondly, ID changes is not so much time as CSS.

How can we pick html elements value using web driver

Hi i want to get value of html element using web driver how can i get it?I am explaining the scenario as below. I have a span element as below with value between the starting and closing tag .How can i get it?
<span id="foo">
some value
</span>
You have to use the webElement.getText() for that.
I worte a small unit test for you:
public class TestGetText
{
#Test
public void shouldReadSomevalue()
{
final WebDriver webDriver = new HtmlUnitDriver();
webDriver.get("http://s2server.de/stackoverflow/11719445.html");
final WebElement webElement = webDriver.findElement(By.id("foo"));
final String text = webElement.getText();
assertEquals("some value", text);
}
}
Try below solution -
String test = driver.findElement(By.id("lbHome")).getText();
System.out.println(test);
Try locating the element using XPath instead of ID, then using either
driver.findElement(By.xpath(“xpath for your lbl“)).getText()
or
String st = driver.findElement(By.xpath(“xpath to your lbl“)).getAttribute(“value”);
Source : SeleniumWiki