Not Able to click in Radio Button - Selenium - java

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.

Related

WebElement getText() Returns empty value

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.

isSelected() , isDisplayed is not working for me in selenium,java for checkbox. Where xpath doesn't show if it is checked or unchecked

isSelected() , isDisplayed is not working for me in selenium,java for checkbox. Where xpath doesn't show if it is checked or unchecked.
<input aria-label="Resi" checked="checked" class="curam-checkbox "
id="__p3id" name="__p3id" title="Resi" type="checkbox" value="true">
<label aria-hidden="true"
class="checkbox-touchable-area" for="__p3id"
title="Resi"> </label>
#FindBy(xpath="//label[contains(#title,'Resi')]")
private WebElement resiCheckbox;
public void clickResi() throws Exception {
waitUntilTheElementIsVisible(resiCheckbox);
if(!resiCheckbox.isSelected())
resiCheckbox.click();
}
if(!resiCheckbox.getAttribute("checked").equals("checked"))
resiCheckbox.click();
or
if(!resiCheckbox.getAttribute("value").equals("true"))
resiCheckbox.click();
One of them should work.
Show example of your java code, so we can help you.
Or try as show in example:
driver.findElement(By.id("__p3id")).isSelected;
In addition. Try this:
//Driver initialized by Chrome browser driver
WebDriver driver = new ChromeDriver();
//Creating wait driver. In constructor we passing WebDriver by the first parameter
// and max time to wait in seconds by the second parameter
WebDriverWait wait = new WebDriverWait(driver, 5);
//Loading URL
driver.get("Your URL");
//Finding checkBox WebElement by id
WebElement resiCheckbox = driver.findElement(By.id("__p3id"));
//Waiting element to be clickable (max time to wait = 5 sec)
wait.until(ExpectedConditions.elementToBeClickable(resiCheckbox));
//Clicking if checkBox toggled off
if(!resiCheckbox.isSelected())
resiCheckbox.click();

Unable to Click button in Selenium

Im having difficulties in locating an element which is a finish button within a page. I have used driver.findElementById("finish").click (); and it does not work.
Below are different examples I used but with no success:
for (WebElement Element : driver.findElement(By.id("finish")).findElements(By.tagName("a"))) {
if (Element.getAttribute ("class").contains("criteria-filter")) { Element.click();
break;
}
----------------------------------------------------------------
WebElement click1 = new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"finish\"]")));
((JavascriptExecutor) driver).executeScript("arguments[0].click();",click1);
----------------------------------------------------------------
if(!driver.findElementById("finish").isEnabled())
{
driver.findElementById("finish").click();
}else{
System.out.println("False");
}
Element:
<a id="finish" access="" allof="PA.DEPLOYMENT_CONFIG" class="btn criteria-filter btn-success" href="" ng-click="verifyAllFields(sftpForm) && sftpForm.$valid && create()">Finish
</a>
Class selector is not the best idea as it will fail if there is more elements with the same class.
The best way is to open dev-tools, click ctrl + f, then try to cath your element by xpath like this:
//a[text()='Finish']
When you "cath" this browser will move to that element.

Selenium WebDriver - Using Java - How can I check if error messages are visible or not in a webpage?

I am testing a webpage that does some user error validation. When the webpage first appears, no error messages should appear, so I need to check for that. Then, depending upon the error (sometimes after clicking “submit” other times after the user enters data), I need to verify that the correct error messages appear.
In the code below, no error message should appear when the webpage is first loaded, but if I don’t enter a date and click the submit button, the error message should appear.
<div id="showNotIE" style="display: none;">
<input id="txtImplantDate" class="ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required" type="date" required="" placeholder="YYYY-MM-DD" name="txtImplantDate" ng-model="ImplantInsert.ImplantImplantDate">
</div>
<div class="ng-scope" ng-if="showMsgs && (Currentdate < newDate)" style="">
<span style="color:red;">Implant Date cannot be greater than today and is required</span>
Using the Java code below, this seems to function properly (the first check in the IE 11 browser takes a REALLY LONG TIME, but it does appear to work).
//Confirming text is not visible
boolean isPresent = driver.findElements(By.xpath(textLocator)).size() > 0;
if (isPresent) {
//Write to log that text is present (FAIL)
} else {
//Write to log that text is not present (PASS)
} //end if
This code also seems to work:
//Confirming text is not visible
boolean isEmpty = driver.findElements(By.xpath(textLocator)).isEmpty();
if (isEmpty) {
//Write to log that text is not present (PASS)
} else {
//Write to log that text is present (FAIL)
} //end if
However, when I test against this HTML code and use the same Selenium WebDriver Java logic to test, I get the wrong results.
<select id="selPatientTypes" class="fontInput ng-pristine ng-untouched ng-empty ng-invalid ng-invalid-required" required="" name="selPatientTypes" ng-options="n.PatienTypeID as n.PatientTypeDescription for n in scPatientTypes | filter:FilterPatientTypes" ng-model="ImplantInsert.ImplantPatientTypeID">
<option class="" value="" selected="selected">-- Please select Patient Type --</option>
<option label="Adult" value="number:1">Adult</option>
<option label="Pediatric" value="number:2">Pediatric</option>
</select>
<span class="ng-hide" style="color:red;" ng-show="showMsgs && ImplantForm.selPatientTypes.$error.required">Patient Type is required</span>
If I try using this “isDisplayed” code, Java errors out.
try {
boolean xpathIsDisplayed = driver.findElement(By.xpath(fieldLocator[value])).isDisplayed();
// Write to log that text is present (FAIL)
} catch (Error e) {
//Write to log that text is not present (PASS)
} //end try
The error message is:
org.openqa.selenium.NoSuchElementException: Unable to find element with xpath == //div[2]/table[2]/tbody/tr[1]/td[2]/div[3]/span (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 30.06 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html (BTW: This URL doesn’t provide any useful information)
This is another type of error logic that is used on the webpage.
<input id="txtPatientBSA" class="fontInput ng-pristine ng-untouched ng-valid ng-empty ng-valid-maxlength" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1'); " title="Patient BSA should be in range of 0 to 5.00 (X.XX)" ng-keyup="ValidateBSA()" style="direction: rtl" max="5.00" min="0.00" maxlength="4" size="4" ng-model="ImplantInsert.ImplantPatientBSA" name="txtPatientBSA" placeholder="X.XX">
<span id="ErrorMsgBSA" class="error error-keyup-1 ng-hide" style="color:red;" ng-show="ShowErrorMsgBSA"> Patient BSA should be in range of 0 to 5.00 (X.XX)</span>
Does anyone know if there is a way to check for all types of HTML error message logic and determine if they are visible or not visible on the webpage?
Thanks.
I'm guessing the reason your first error code takes a really long time is because you have an implicit wait set for a long time. Implicit waits will wait for the specified amount of time for an element to appear. In the case of an error message that isn't there, it will wait for the timeout period and then move on which makes your code execute slowly. I would remove the implicit wait and add explicit waits where needed. The second error is just saying that it can't find the element with the given XPath. You probably need to update your XPath or use another locator.
Here's a Java function that you can pass your desired locator into and it will return true if the element exists and is visible.
/**
* Returns whether an element is visible
*
* #param locator the locator to find the desired element
* #return true if the element exists and is visible, false otherwise
*/
public boolean IsVisible(By locator)
{
List<WebElement> elements = driver.findElements(locator);
if (elements.isEmpty())
{
// element doesn't exist
return false;
}
else
{
// element exists, check for visibility
return elements.get(0).isDisplayed();
}
}
For the element below,
<span id="ErrorMsgBSA" class="error error-keyup-1 ng-hide" style="color:red;" ng-show="ShowErrorMsgBSA"> Patient BSA should be in range of 0 to 5.00 (X.XX)</span>
you could use the locator, By.id("ErrorMsgBSA").
For the element below,
<span class="ng-hide" style="color:red;" ng-show="showMsgs && ImplantForm.selPatientTypes.$error.required">Patient Type is required</span>
you could use a CSS selector like, "span.ng-hide" which just means find a SPAN that contains a class (.) ng-hide.
A CSS Reference
CSS Selector Tips
you should add findElement in try catch block and use findElement instead of findElements (Xpath is a unique).
Use for construction. the point is that your element can be there, but the selenium may not be able to find it at once. So you need to check it more then once and wait a little after every iteration.
WebElement element = null;
boolean flag = false;
for (int i = 0; i< 10; i++) {// iterating 10 times
try {
element = driver.findElement(By.xpath("yourXpath"));
if (element != null) {
flag = true;
break;
}
} catch (Exception e) {
//you can log or whatever you want
}
pause(1000); //after iteration wait for a second ,
//so it will give a time to load the DOM
}
if(flag){
//your code goes here
}else{
//your code goes here
}

Selenium: Why .click() doesn't work in this case && how to check if a button is clicked?

Title edited: was "Selenium: How to check if a link is opened in a new tab?"
I need to create JUnit test which should check if click on a button will cause opening some link in new tab.
Doing that I've faced the problem: looks like .click() doesn't do what it suppose to.
Here's the fragment of HTML:
<div class="small-5 column store-btns">
<a class="google_play_btn" target="_blank" href="https://google.com">
<img class="img-responsive"src="/s/img/buy/google_play_btn_blue.svg" alt>
</a>
<a class="app_store_btn" target="_blank" href="https://apple.com/">
<img class="img-responsive"src="/s/img/buy/app_store_btn_blue.svg" alt>
</a>
</div>
EDITED: Here's my simple JUnit test:
#Before
public void SetUp(){
driver = new SafariDriver();
pause = new WebDriverWait(driver, 2000);
}
#After
public void tearDown(){
driver.close();
driver.quit();
}
#Test:
public void testLink() throws InterruptedException{
driver.get("http://linktotestedpage");
WebElement googlePlayButton = pause.until(ExpectedConditions.visibilityOfElementLocated(By.className("google_play_btn")));
googlePlayButton.click();
List<String> browserTabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(browserTabs.get(1));
String titleGP = driver.getTitle();
Assert.assertTrue("Failure: link is ok", titleGP.equals("Google"));
I expect a new Safari tab to be opened after googlePlayButton.click();, but the driver just quits.
I see
IndexOutOfBoundsException: Index 1, Size 1
Where am I wrong?
Thanks.
I would add an additional check since the windowsHandle is explicitly unordered and there is no guarantee the last tab would be the one with index 1
String currentHandle = driver.getWindowHandle();
List<String> browserTabs = new ArrayList<String>(driver.getWindowHandles());
for (String handle: browserTabs){
if (handle != currentHandle){
driver.switchTo().window(handle);
//perform addition action as needed;
//when done close the window
driver.close();
driver.switchTo().window(currentHandle);
}
}
String titleGP = driver.getTitle();
Note: Untested code from my side
Just One suggestion,
You may remove tearDown section of your code.
to leave browser open, to check whether tab is opening with any delay or not.
what i suspect is, you might be trying to switch to window before it is opened.
Note: should be a comment but don't have that reputation yet.

Categories

Resources