WebElement getText() Returns empty value - java

Following code is used to get a mobile phone's price from amazon using Selenium Webdriver.
If I use /span1 at end in xpath it is not printing anything
If I don't use xpath it prints price
HTML source code for the elements
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.amazon.in");
driver.findElement(By.xpath("//input[#id='twotabsearchtextbox']")).sendKeys("one");
Thread.sleep(2000);
List<WebElement> all_mobile= driver.findElements(By.xpath("//div[#id='suggestions']/div/span"));
//Thread.sleep(2000);
int total= all_mobile.size();
//System.out.println(total);
for(int i=0; i<total;i++)
{
String mobiles = all_mobile.get(i).getText();
//System.out.println(mobiles);
if(all_mobile.get(i).getText().equals("plus nord 5g"))
{
all_mobile.get(i).click();
break;
}
}
Thread.sleep(2000);
String text = driver.findElement(By.xpath("(//span[#aria-label='FREE Delivery by Amazon'])[1]/span")).getText();
System.out.println(text); //it prints FREE Delivery by Amazon working fine if I use /span at end or not both ways but below iam getting issue in price
String price = driver.findElement(By.xpath("(//span[#class='a-price'])[1]/span[1]")).getText();
System.out.println(price); //it prints nothing if iam using /span[1] at end
String PRICE = driver.findElement(By.xpath("(//span[#class='a-price'])[1]")).getText();
System.out.println(PRICE); //it prints ₹29,990 if iam not using /span[1] at end
Can anyone please help? Why I am getting different outputs with getText()?

Price text is coming from the second span element. <span aria-hidden="true">. First span is hidden by CSS
<span class="a-price" data-a-size="l" data-a-color="price">
<span class="a-offscreen">₹29,990</span>
<span aria-hidden="true">
<span class="a-price-symbol">₹</span>
<span class="a-price-whole">29,990</span>
</span>
</span>
You can get the price from the second span element too
System.out.println("Experiments ");
price = driver.findElement(By.xpath("(//span[#class='a-price'])[1]/span[2]")).getText();
System.out.println(price);
WebElement's getText() documentation shows that
Get the visible (i.e. not hidden by CSS) text of this element, including sub-elements.
<span class="a-offscreen">8888</span> is hidden.

Related

Check that two span classes are equal to text and click on the correct span element after

I have two span elements and I need to check that my text: Frat Brothers (2013) is equal to text inside this span clases and that click on this element.
<a href="/frat-brothers" class="">
<span class="name-content-row__row__title">Frat Brothers</span>
<span class="name-content-row__row--year">(2013)</span>
</a>
My code:
String title = "Frat Brothers (2013)";
List<WebElement> content = driver.findElements(By.cssSelector("span[class*='name-content-row__'"));
for (WebElement e : content) {
System.out.println("elememts is : " + e.getText());
if (e.getText().equals(title)) {
click(e);
}
output:
elememts is : Frat Brothers
elememts is : (2013)
if statment isn't executed.
if statment did not execute, cause you have
String title = "Frat Brothers (2013)";
change that to
String title = "Frat Brothers";
and you should be good to go.
also do not use click(e); instead it should be e.click();
driver.findElements method accepts By parameter while you passing it a String.
In case you want to select elements according to this CSS Selector you can do this:
List<WebElement> content = driver.findElements(By.cssSelector("span[class*='name-content-row__'"));
Also, you will get 2 span elements, first with text Frat Brothers and second with text (2013).
No one of these elements text will NOT be equal to Frat Brothers (2013).
You can check if title contains these texts
You can try the following xPath: //a[normalize-space()='Frat Brothers (2013)']
So that there would be no need for extra code. Like:
String title = "Frat Brothers (2013)";
WebElement content = driver.findElement(By.xpath("//a[normalize-space()='" + title + "']"));
content.click();
P.S. - Here is the xPath test: http://xpather.com/V9cjThsr
Text verification, add testng dependency in your pom.xml
String title = "Frat Brothers (2013)";
// storing text from the element
String first = driver.findElements(By.cssSelector("span[class*='name-content-row__'")).get(0).getText();
String second = driver.findElements(By.cssSelector("span[class*='name-content-row__'")).get(1).getText();
// validating the text
Assert.assertTrue(title.contains(first), "checking name is available in the element");
Assert.assertTrue(title.contains(second), "checking year is available in the element");

Not Able to click in Radio Button - Selenium

Tried to select from Radio Button, Check on Console the Element is there and its not under Iframe:
$x("//*[#id='featuresCollapse1']/div[1]/label/span")
(2) [span.overlay, span.overlay]
HTML:
<div class="col-6 my-1 feature-input-wrapper text-left">
<input name="radio0" data-index="1" id="Personal Accident for Driver only" hidden="" type="radio"><label data-code="PA-DO" data-value="60" class="radio-inline custom-component featureInput p-0 radio-no form-group">
<span class="overlay" tabindex="0"></span>
<label data-value="60" class="feature-name">Personal Accident for Driver only<span class="option-price font-weight-bold ml-2"> 60 </span> </label></label></div>
the Xpath of the radio is : private final By PAforDriverOnly = By.xpath("//*[#id='featuresCollapse1']/div[1]/label/span");
Tried here to check if it Display or not .. but its not " Reading the Exception message
try {
driver.findElement(PAforDriverOnly).isDisplayed();
System.out.println("driver.findElement(PersonalAccindent).isDisplayed();");
String Persional = driver.findElement(PAforDriverOnly).getText();
System.out.println(Persional);
driver.findElement(PAforDriverOnly).click();
System.out.println("driver.findElement(PersonalAccindent).click();");
//getTextAct(ProceedToCheckoutBtn);
} catch (Exception e){
System.out.println("The Exception Message of Verify Button : "+e);
}
and here tried to use JavaScriptExcutor, but Failed on WebDriverWait,
once to remove it, its reading the JavaExcutor but not Give any Action :
WebElement myElement = driver.findElement(PAforDriverOnly);
new WebDriverWait(driver, 5).until(ExpectedConditions.visibilityOfElementLocated(PAforDriverOnly));
((JavascriptExecutor)driver).executeScript("arguments[0].click();", myElement );
System.out.println("JavaScriptExcutor - Click on RadioButton");
Thread.sleep(2000);
Btnclick(PAforDriverOnly);
I hope your xpath is wrong,
because your xpath is pointing to label. try to point it to input tag.
use this //input[#id='Personal Accident for Driver only'] or use it on your way to find the element but you need to drill down to input tag.

Webdriver - getting div value using java

Html
<div class="rc-anchor-light">
<div id="accessible-status" class="rc-anchor-aria-status" aria-hidden="true">requires verification.</div>
</div>
My expected
Extract the text from inside the div "requires verification."
tried below locator, but i'm not getting my expected.
unique id so i tired with id getting empty result
String accessText = driver.findElement(By.id("accessible-status")).getText();
using class name getting empty result
String accessText = driver.findElement(By.className("rc-anchor-aria-status")).getText();
Please suggest me how to get the value.
Text content of target div node might be generated dynamically. Try to implement ExplicitWait for element with any text:
WebDriverWait wait = new WebDriverWait(webDriver, 10);
WebElement divNode = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#id='accessible-status' and normalize-space()]"));
String accessText = divNode.getText();
If element has text from the very beggining, but it is just hidden, getText() will not return you text. In this case you may try
String accessText = driver.findElement(By.id("accessible-status")).getAttribute("textContent");
As per the HTML you have shared to extract the text requires verification. from the div you need to use a Locator Strategy to identify the WebElement uniquely and induce WebDriverWait with ExpectedConditions set as visibilityOfElementLocated(By locator) for the WebElement to be visible in the HTML DOM and finally use getAttribute() method to to extract the text. You can use the following line of code :
System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#class='rc-anchor-light']/div[#class='rc-anchor-aria-status' and #id='accessible-status']"))).getAttribute("innerHTML"));

How to get content from span with Jsoup

I am using Jsoup HTML parser to extract content from a HTML page.
<span class="mainPrice reduced_">
<span class="oPrice" data-test="preisArtikel">
<span itemprop="price" content="68.00"><span class="oPriceLeft">68</span><span class="oPriceSeparator">,</span><span class="oPriceRight">00</span></span><span class="oPriceSymbol oPriceSymbolRight">€</span>
I want to extract the content (68.00) and I tried following:
Elements price = doc.select("span.oPrice");
String priceString = price.text();
That doesn't work because the class "oPrice" occurs 44 times in the page and the string "priceString" contains 44 different prices.
Thank you for your help.
Try this:
//For one element
Element elements = document.select("span[content]").first();
System.out.println(elements.attr("content"));
If you have multiple like same span
//For multiple
Elements elements = document.select("span[content]");
for (Element element:elements){
System.out.println(element.attr("content"));
}
Output:
68.00
On top of that Check JsoupSelector for the reference.

How to verify the button having drop down menu using selenium in java

There is a button. When you click on this button, a drop down menu having two option appears. How to verify this scenario using selenium in java.
<div class="hpDropDownButton">
<button class="button ng-binding">Holidays Operation</button>
<ul>
<li>
<a class="ng-binding" ng-click="uploadHolidays()">Upload Holidays</a>
</li>
<li>
<a class="ng-binding" ng-click="deleteHolidays()">Delete Holidays</a>
</li>
</ul>
Click on the button
Now :-
Boolean dropdownPresent = driver.findElement("YOUR LOCATOR OF DROPDOWN").isDisplayed();
if(dropdownPresent==true)
{
System.out.println("Dropdown is appearing");
}
else{
System.out.println("Dropdown is not appearing");
}
Hope it will help you :)
You are asking to verify whole scenario. You need to first understand what Selenium-WebDriver is. Refer this tutorial for more explanation.
However you can follow below code,
WebDriver driver = new FirefoxDriver();
String appUrl = "your url";
driver.get(appUrl);
// maximize the browser window
driver.manage().window().maximize();
// upto code from your button
WebElement button_element = driver.findElement(button_locator);
button_element.click();
// to verify a drop down menu having two option appears
boolean flag = isPresent(dropdown_locator);
if (flag) {
// code bases on dropdown displayed
}
else {
// code bases on dropdown not displayed
}
To verify if element is present or not use this method
public boolean isPresent(String locator) {
return findElements(locator).size() > 0 ? true : false;
}
First of all collect all the Drop down values in List, List values = Upload Holidays#Delete Holidays
Then click on Dropdown WebElement, by using DropdownFieldName = driver.findElement(by.xpath(//button[#class='button ng-binding'])).click();
Take the couunt of dropdown values, by drptotalCount = driver.findElements(by.xpath(//a[#class='button ng-binding']));
Now you have expected DropDown values and count of Dropdown Values.
You can take a reference from below code:
checkDropDownValues(String DropdownFieldName, String values){
driver.findElement(By.xath(DropdownFieldName)).click();
WebElement drptotalCount = driver.findElements(by.xpath(//a[#class='button ng-binding']));
int numberOfDropDown = drptotalCount.size();
List<String> allDropDownValues = Arrays.asList(values.split("#"));
for (int colCount = 1; colCount <= numberOfDropDown; colCount++) {
boolean flag = false;
Actualvalue = driver.findElement(By.xpath(drptotalCount + "[.=" + allDropDownValues.get(colCount) +"]"])).getText();
String expectedValues = allDropDownValues.get(colCount);
if(expectedValues.equalIgnoreCase(Actualvalue))
{
flag = true;
}
Assert.assertTrue("Column values doesn't match", flag);
}
}
Click the button (which should be straight forward)
it seems you have some asynchronous call or a delay
Wait for the drop-down 'div.hpDropDownButton' is beeing displayed using WebDriverWait:
WebElement myDynamicDropDown = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.CssSelector("div.myDynamicDropDown")))
continue ..
http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp

Categories

Resources