Get the value from xpath in selenium - testing

How can I get the value from xpath in Selenium.
public void DummyFunc(String startDate){
String test;
test=driver.findElement(By.xpath("//startDate"));
}
I am passing the location of the table like table > tr > td but I am getting an error when I use String.

Your answer need more precision. If "by value" you mean "text", you can have it with getText() method (it return the innerHTML):
public void DummyFunc(String startDate){
String test;
test = driver.findElement(By.xpath("//"+startDate));
return test.getText()
}
edit :
btw, table > tr > td is not a valid xpath string. It should be //table/tr/td

Related

Get error [object Text]. It should be an element

Trying to get the text from the div with xPath. Finds information in the browser good, but when i try to run with an idea than i get error:"is: [object Text]. It should be an element."
List<WebElement> priceGameWebElement = webDriver.findElements(By.xpath("//div[contains(#class,'search_price')]" +
"/text()[normalize-space()][1]"));
What do I need to do to make everything work?
You can "interrupt" your query before the /text()... part like this:
List<WebElement> priceGameWebElement = webDriver.findElements(By.xpath("//div[contains(#class,'search_price')]"));
Then you should get a List<WebElement> which contains the elements with the text() nodes for further distinction. They could probably be queried with the .getText() function.
If for some reason you cannot exclude text() from XPath and you need just extract the text of the element, then there is a workaround: use method document.evaluate() from JavaScript.
Code example:
String textObjectXpath = "\"//*[local-name() = 'text'][#x='8']/text()\"";
String script = "var element = document.evaluate("
+ textObjectXpath
+ ", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;"
+ "if (element) {return element.nodeValue;}";
String extractedText = (String) ((JavascriptExecutor)driver).executeScript(script);
The if statement "if (element) {return element.nodeValue;}" could be omitted if you don't care about the scenario when the element will be without text. In a such case, you may want to replace the line with "return element.nodeValue;"

Xpath con-cat is possible with reference to List<WebElement> object in selenium?

Scenario with Example:
10 Different Row in Table (e.g. //a[#class='*******'] ).
Need to Retrieve different Value from each Row
Retrieving it using List
In given example, Temp1 getting executed and iterate as required, As information need to retrieve from the same and got it through getAttribute(" ").
Need to retrieve Temp2 value which is dependent on object findList. findSubInfo is having Following Siblings from mainList. Its only addition on following siblings in to List exa.(findList).
Issue is :
If I execute 1st provision, as independent node, It always retrieve first row's value. (Which is Obvious)
If I execute 2nd provision, with xpath + List object using con-cat it throws xpath Syntax issue.
Question :
How can retrieve all information from object's siblings, where object List<WebElement> findList is pointing ?
Trial :
By mainList = By.xpath("//a[#class='*******']");
By findSubInfo = By.xpath("//a[#class='*****']//following::div[#class='****']");
List<WebElement> findList = driver.findElements(mainList);
for (WebElement webElement : findList ) {
if (webElement.isDisplayed()) {
String temp1= "Info1:" + webElement.getAttribute("ng-href");
String temp2= "Info2: " + driver.findElement(findSubInfo).getText();
}
}
OR
String mainList "//a[#class='*******']";
String findSubInfo = "//following::div[#class='****']";
List<WebElement> findList = driver.findElements(By.xpath(mainList));
for (WebElement webElement : findList ) {
if (webElement.isDisplayed()) {
String temp1= "Info1:" + webElement.getAttribute("ng-href");
String temp2= "Info2: " + driver.findElement(By.xpath(webElement + findSubInfo )).getText();
}
}
Exception Details:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string
'[[ChromeDriver: chrome on XP (3208ef0a2ffd32812c33e159291eebe4)] ->
xpath: //a[#class='noDecoration
addPointer']]//following::div[#class='assignedAccountMasterAddress']'
is not a valid XPath expression.
If you want to search for element with related XPath starting from current element (webelement), try
# Note that it should start with the dot
String findSubInfo = "./following::div[#class='****']";
# use webElement.findElement instead of driver.findElement. No XPath concatenations needed
String temp2= "Info2: " + webElement.findElement(By.xpath(findSubInfo)).getText();

Dropdown duplicate value automation using Selenium

How to check the duplication of values in a checkbox using Selenium Webdriver
something like the below one will work if both the options have same value
public boolean isSelectOptionsRepeating(WebElement dropdown)
{
Select s = new Select(dropdown);
List<WebElement> list = s.getOptions();
Set<String> listNames = new Hashset<String>(list.size());
for (WebElement w : list) {
listNames.add(w.getText().trim());
}
if(list.size()== listNames.size())
return true;
else
return false;
}
You can store the values of drop down in String array and
traverse string array and use Hashmap for storing the values from the dropdown and if duplicate occurs increement the count by one
voila......you would know the the Values with its count, if count > 1. Duplicate
for reference : Java Beginner - Counting number of words in sentence

Searching and Selecting value from dropdown using selenium Webdriver

I want to know how to select a specific value from dropdown from a pool of values.
My logic is
1.Open the page
2.Fetch all the values from dropdown in list
3.Use a loop
4.Look for that value
5.If the value is not there,select the value x
For me it is saying No such Element Exception
Is it do we need to focus on that element first
In my code i want to select Nextran Corporation
Below is my code
#Test(dependsOnMethods={"go2personalsettings"})
void setru()
{
driver.switchTo().frame("contentFrame");
Select rudropdown=new Select(driver.findElement(By.id("DefaultOrganisationDropDown")));
List<WebElement> drop=rudropdown.getOptions();
int e=drop.size();
String actual_ru="999425, NEXTRAN CORPORATION - JACKSONVILLE";
for(int i=0;i<e;i++)
{
String expected_ru=drop.get(i).getText();
if(!expected_ru.equals(actual_ru))
{
rudropdown.selectByValue(actual_ru);
}
}
Try This:
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//li[contains(text(),'" + ElementValue + "')]")));
WebElement webElement = driver.findElement(By.xpath("//li[contains(text(),'" + ElementValue + "')]"));
webElement.click();
The logic in your code doesn't match what you stated was your intent. You stated that you want to select a particular value from the dropdown, if it exists. If it doesn't, select value 'x'. Your code doesn't ever select value 'x' so I'm not sure what 'x' is but you can fill that in below. Basically the code attempts to select the expected value. If that expected value does not exist, it will throw an exception which is caught and then 'x' is selected. If it does exist, the value is selected and selecting 'x' is skipped.
driver.switchTo().frame("contentFrame");
Select rudropdown = new Select(driver.findElement(By.id("DefaultOrganisationDropDown")));
String actual_ru = "999425, NEXTRAN CORPORATION - JACKSONVILLE";
try
{
rudropdown.selectByValue(actual_ru);
}
catch (NoSuchElementException e)
{
// expected value does not exist, select the value x instead
rudropdown.selectByValue("x");
}

Selenium WebDriver get text from input field

I'm writing a test to assert the default text value within an <input> tag. However, it's not playing ball:
Assert.assertThat(webDriver.findElement(By.id("inputTag")).getText(), Matchers.is("2"));
This is the input element - you need to get the value attribute:
webDriver.findElement(By.id("inputTag")).getAttribute("value")
The most reliable solution I found, is executing a JavaScript script and return the value attribute of the HTMLInputElement from JavaScript.
I have tested this in several ways and the value was always correct, even after changing the input field value.
PHP
$input = $driver->findElement( WebDriverBy::id( 'inputTag' ) );
$value = $driver->executeScript( 'return arguments[0].value', $input );
// A custom PHP function that returns the value of an input field:
function getValue(RemoteWebDriver $driver, WebDriverBy $by ) {
return $driver->executeScript(
'return arguments[0].value',
$driver->findElement( $by )
);
}
// Sample usage:
$value = getValue( $driver, WebDriverBy::id( 'inputTag' ) );
Java
//driver being your WebDriver
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement inpElement = driver.findElement(By.id("inputTag"));
String text = (String) js.executeScript("return arguments[0].value", inpElement);