Find checkbox and add text - java

I would like to add in the secondary text field at this website a text string.
My selenium method looks like the following:
public void addSecondaryText(String string) {
//click secondary button
WebElement secButton = driver.findElement(By.xpath("//label/input[#id='sub-text-check']"));
if (secButton.isDisplayed()) {
secButton.click();
}
//clear text
WebElement secTextField = driver.findElement(By.xpath("//*[#id='sub-text']"));
secTextField.clear(); // I get the exception here!
//add text
secTextField.sendKeys(string);
}
However, I currently get an exception for secTextField.clear();, that it cannot be manipulated:
Exception in thread "main" org.openqa.selenium.InvalidElementStateException: invalid element state: Element is not currently interactable and may not be manipulated
Any suggestions what I am doing wrong?
I appreciate your replies!

The issue here is that the textarea depends on another button and you need to perform a click on it before making the textarea editable. See the image below.
//List will help of to determine the "Add secondary text" button needs to be clicked on not
//if the count is greater than 0 then click it
IList<IWebElement> elements = driver.FindElements(By.XPath("//span[contains(text(),'Add secondary text')]"));
if (elements.Count>0)
{
elements.FirstOrDefault().Click();
}
IWebElement element = driver.FindElement(By.Id("sub-text"));
element.Clear();
element.SendKeys("Test");

Following code should work -
public void addSecondaryText(String string) {
//click secondary button
WebElement secButton = driver.findElement(By.xpath("//span[#class='sub-text-toggle']"));
secButton.click();
//clear text
WebElement secTextField = driver.findElement(By.xpath("//*[#id='sub-text']"));
secTextField.clear(); // I get the exception here!
//add text
secTextField.sendKeys(string);
}

Related

How to enable button do verify in Selenium WebDriver?

I have one button section product, but it disables when hover mouse on section product then the button is enabled. I don't know write script do enable a button when Selenium WebDriver finds it.
#Test(priority = 4)
public void TestSelectedItem() {
driver.findElement(By.xpath("/html/body/app-root/ng-component/div/product-list/div/div/div/div/div[2]/div/div[3]/div/div[1]/a")).click();
Select drpItem = new Select(driver.findElement(By.id("pa_colors")));
drpItem.selectByIndex(2);
driver.findElement(By.className("add_to_cart_button")).click();
}
Please help me.
I will give you code in Python which do hover action on the element:
hover_company = driver.find_element_by_xpath("your XPath")
driver.execute_script("arguments[0].scrollIntoView(true);", hover_company)
hover = ActionChains(driver).move_to_element(hover_company)
hover.perform()
First two lines scroll to your element, last two lines -- do hover action on the element.
After this action -- you can click on the button. Try on.
Code in Java:
hover_company = driver.findElement(By.xpath("your XPath"));
driver.executeScript("arguments[0].scrollIntoView(true);", hover_company);
Actions hover = new Actions(driver);
hover.moveToElement(hover_company).perform();

How to handle a pop-up window when that shows up at uncertain time?

I am trying to automate test cases. It's difficult since the pop message appears at uncertain time as a result the test case fails. Sometimes pop-up appears without a click and other times it is 5-6 clicks before the pop-up appears. I can't locate the pop-up there is no id or XPath.
If popup is windows based then use AutoIT library.
If it is web popup then you can handle it by following code
Set<String> set = driver.getWindowHandles();
List<String> list = new ArrayList<>(set);
// store your main window handle in variable
String mainWindow = list.get(0);
// To close all unwanted popup
for(int i =1; i <list.size(); i++)
{
String unwantedPopup = list.get(i);
driver.switchTo().window(unwantedPopup);
driver.close();
}
// Switch back to your main window
driver.switchTo().window(mainWindow);
I found solution that works for me.
Thread.sleep(5000); //wait for the modal message to appear
String winHandleBefore = driver.getWindowHandle();
driver.findElement(By.xpath("xpath")).click();
Thread.sleep(2000);
driver.switchTo().window(winHandleBefore);

Selenium Java, How to check if multiple radio buttons are selected?

I am working on a framework and have tried the following and not results :
List<WebElement> rows = EarningNormal.oRdioList;
java.util.Iterator<WebElement> i = rows.iterator();
while(i.hasNext()) {
WebElement ContribIDYES = i.next();
//System.out.println(sitcodes.getText());
if(ContribIDYES.isSelected()){
TestDriver.globalProps.getHtmlReport().writeHTMLReport("Contribution ID Formulas must be set to Yes as default", "Contribution IDs must be set to YES ", "All Contribution IDs must be YES","Contribution ID's are set to YES" , "PASS", "Done");
}
else{
TestDriver.globalProps.getHtmlReport().writeHTMLReport("Contribution ID Formulas must be set to Yes as default", "Contribution IDs must be set to YES ", "All Contribution IDs must be YES", "Contribution ID's are NOT seto to YES as default", "FAILED",TestDriver.comUtil.getImageFileLoc(TestDriver.globalProps.getWebDriver()));
}
}
Hi when you want to verify if a radio button is selected or not then please pay attention that any input tag with type radio has a hidden attribute value known as selected if a radio button is selected then its value is = True and if not then its value is = null,hence on the basis of this you can easily identify which radio button is selcted or not .below find a working example for the same
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("C:\\Users\\rajnish\\Desktop\\myradio.html");
// working with radio buttons
// first take all the radio buttons inside a list like below
List<WebElement> myradioloc = driver.findElements(By.xpath("//*[#type='radio']"));
// apply the for loop to identify/ verify if a radio button is selected or not
for(int i=0;i<myradioloc.size();i++){
System.out.println("attribut value Selected of radio button is : " + myradioloc.get(i).getAttribute("selected"));
// if radio button is selected then value of selected attribute is True else null
if( myradioloc.get(i).getAttribute("selected").equals("null")){
// as if loop will only run when value of selected attribute is null
// i.e only when radio button is not selected
myradioloc.get(i).click();
}
}

How to get an active window title between two browser tabs/windows using Selenium Java

I can switch between two tabs/windows but my requirement is to know or get active window between them.
In my project, on a click of a webElement of a page a random pop(tab/window) gets opened and I would like to know whether that(new) window has focus or my original page.
I tried to use JNA Api to get the active window and its title but my web page is
remotely located.
Perfect solution is greatly appreciated.
Thanks
driver.getTitle() will give you the title of the page that you can use to determine which page you are on or if you are on the page where you want to be and then use the logic to switch window if required. getTitle() returns a String and you can use one of the string methods to compare the title, for example:
String title = getDriver().getTitle();
if(!title.equals("Expected Title")) {
//may be you would like to switch window here
}
String title = driver.getTitle()
This will give you the title of the page which you can refer to using Selenium to figure out which page the driver is currently on.
I wrote my own method to switch to a window if the window title is known, maybe some of this would be helpful. I used Selenide (Java) methods for this, but if you've got Vanilla WebDriver, you can achieve the same thing
/** Switches user to window of user's choice */
public static void switchToWindow(String windowTitle) {
WebDriver driver = getWebDriver();
// Get list of all open tabs - note behaviour may be different between FireFox and Chrome.
ArrayList<String> tabs = new ArrayList<>(driver.getWindowHandles());
// iterate through open tabs. If the title of the page is contained in the tab, switch to it.
for (String windowHandle : driver.getWindowHandles()) {
String title = getWebDriver().getTitle();
driver.switchTo().window(windowHandle);
if (title.equalsIgnoreCase(windowTitle)) {
break;
}
}
}
This method might not be lightening fast, but it will iterate through current open windows and check the title matches the one you've specified.
If you want to assert the title, you could use the xpath selector:
String pageTitle = driver.findElement(By.xpath("//title[text() = 'Title you looking for']"));
This is a dumb example with you can surround with try/catch, implement assertions or other technique to have the result you need.
In JavaScript, for me this worked. After clicking on the first link of bing search results in edge, my link opened in a new tab. I explicitly mentioned to stay in the same tab.
async function switchTab() {
await driver.getAllWindowHandles().then(async function (handles) {
await driver.switchTo().window(handles[1]);
});
}
//get initial window handles
Set<String> prevWindowHandles = driver.getWindowHandles();
while(true){
//get current window handles
Set<String> currWindowHandles = driver.getWindowHandles();
//if one of the current window handles not equals to
//any of the previous window handles,switch to this window
//and prevWindowHandles = currWindowHandles
for(String prevHandle : prevWindowHandles){
int noEqualNum = 0;
for(String currHandle : currWindowHandles){
if(!currHandle.equals(prevHandle))
noEqualNum++
}
if(noEqualNum == currWindowHandles.size()){
driver.switchTo().window(currWindow);
prevWindowHandles = currWindowHandles;
break;
}
}
}

Need help on find the textbox in the newly opened window in selenium webdriver

String parentHandle = driver.getWindowHandle();
driver.findElement(By.id("ImageButton5")).click();
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
driver.findElement(By.id("txtEnterDescription")).sendKeys("Test");
driver.findElement(By.id("chklstAllprocedure_0")).click();
I used this code and I got the error as
"Exception in thread "main"
org.openqa.selenium.NoSuchElementException: Unable to find element
with id == txtEnterDescription (WARNING: The server did not provide
any stacktrace information) Command duration or timeout: 30.05
seconds". The HTML code for this text box is ""
Please help me out of this
you may face "NoSuchElementException" only in two case for sure.
1.The Element is yet to be Loaded
- Have an appropriate wait logic here.
2. You may try to locate the element wrongly .
- Double Check your Xpath/ID(what ever)
- Make sure you are in the same frame where the element is present.If not, switch to the frame then.
Just make sure you are switching to the right window
Reason 1 : Just make sure you are switching to the right window
I have an utility method to switch to the required window as shown below
public class Utility
{
public static WebDriver getHandleToWindow(String title){
//parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
WebDriver popup = null;
Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
System.err.println("No of windows : " + windowIterator.size());
for (String s : windowIterator) {
String windowHandle = s;
popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
System.out.println("Window Title : " + popup.getTitle());
System.out.println("Window Url : " + popup.getCurrentUrl());
if (popup.getTitle().equals(title) ){
System.out.println("Selected Window Title : " + popup.getTitle());
return popup;
}
}
System.out.println("Window Title :" + popup.getTitle());
System.out.println();
return popup;
}
}
It will take you to desired window once title of the window is passed as parameter. In your case you can do.
Webdriver childDriver = Utility.getHandleToWindow("titleOfChildWindow");
and then again switch to parent window using the same method
Webdriver parentDriver = Utility.getHandleToWindow("titleOfParentWindow");
This method works effectively when dealing with multiple windows
Resaon 2 : wait for the element
WebdriverWait wait = new WebdriverWait(driver,7000);
wait.until(ExpectedConditions.visbilityOfElementLocatedBy(By.name("nameofElement")));
Reason 3 : check if the element is in a frame if yes switch to the frame before
driver.switchTo.frame("frameName");
Let know if it works ..
Guess the problem is in your switch to logic. I think when you are switching it is passing the code of the parent instead of the child. For this scenario create two local variables parent and child. Loop through the window handles using an iterator and set the parent and child window id's to the variables and pass the child id to the switchTo method. This should work. Keep me posted. Happy coding.

Categories