How to click on the element using Selenium Webdriver - java

I'm trying to click on a pop-up alert message on a UI with Selenium Webdriver.
The problem is, it is not clicking on accept or cancel even if I explicitly and implicitly wait. Is there any other alternative to clicking on a pop-up message. I tried to send key by Robot and press enter, but it did not work too.
click ok popup message function:
try {
WebDriverWait wait = new WebDriverWait(driver, 40);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
report.log(LogStatus.INFO, "Displayed Pop-up Window Alert Message -> " + alert.getText() + " for the Field -> " + fieldName);
System.out.println("Displayed Pop-up Window Alert Message -> " + alert.getText() + " for the Field -> " + fieldName);
alert.accept();
Thread.sleep(3000);
} catch (NoAlertPresentException ex) {
System.err.println("Error came while waiting for the alert popup. ");
report.log(LogStatus.INFO, "Alert pop up box is NOT populating when user clicks on: ");
}
this is what the html looks like for the popup:
<input type="submit" name="ctl00$ctl00$Content$ContentPlaceHolderMain$Continue" value="Continue..."
onclick="if(warnOnDelete('ctl00_ctl00_Content_ContentPlaceHolderMain_EditRadioOptions_1',"
+ "'Please confirm if you wish to delete.') == false) return false;"
id="ctl00_ctl00_Content_ContentPlaceHolderMain_Continue" style="width:100px;">
It has to be in IE, we are not allow to use anything except IE
Update: function for the confirm boxes
function warnOnDelete(deleteButtonID, msg) {
var deleteRadioButton = document.getElementById(deleteButtonID);
if (deleteRadioButton != null) {
if (deleteRadioButton.checked == true)
return confirm(msg);
}
return true;
}

Seems the element is not an Alert but an <input> element and to click() on the element you have to induce WebDriverWait for the elementToBeClickable() and you can use either of the following Locator Strategies:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input[id$='_Content_ContentPlaceHolderMain_Continue'][value^='Continue'][name$='Continue']"))).click();
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[contains(#id, '_Content_ContentPlaceHolderMain_Continue') and starts-with(#value, 'Continue')][contains(#name, 'Continue')]"))).click();

Related

Can't click anything, despite switching frames, on frame popup on Indeed when using selenium

I'm trying to submit an application on indeed using Selenium WebDriver.
I've entered jobType, and jobLocation, pressed search, opened up first result, and in new tab, switched focus, and pressed apply. Now, a pop up appears changing the previously 1 iframe on page to 2. I switch to second iframe and then try to send keys to input text field of "name" yet no input field exists
driver.get("https://www.indeed.com");
WebElement what = driver.findElement(By.id("text-input-what"));
what.sendKeys("Java Programmer");
WebElement where = driver.findElement(By.id("text-input-where"));
Thread.sleep(500);
for (int i = 0; i < 20; i++) {
where.sendKeys(Keys.BACK_SPACE);
}
where.sendKeys("Toronto, ON");
WebElement submit = driver.findElement(By.xpath("//button[#class='icl-Button icl-Button--primary icl-Button--md icl-WhatWhere-button']"));
submit.click();
WebElement thirdElement = driver.findElement(By.xpath("/html[1]/body[1]/table[2]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[1]/td[2]/div[9]"));
thirdElement.click();
System.out.println(driver.getWindowHandle());
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
Thread.sleep(3000);
WebElement apply = driver.findElement(By.xpath("//button[#class='icl-Button icl-Button--branded icl-Button--md']//div[#class='jobsearch-IndeedApplyButton-contentWrapper'][contains(text(),'Apply Now')]"));
System.out.println(driver.findElements(By.tagName("iframe")).size());
apply.click();
driver.manage().window().maximize();
Thread.sleep(3000);
System.out.println(driver.getWindowHandle());
driver.switchTo().frame(1);
System.out.println(driver.getWindowHandle());
// Thread.sleep(3000);
System.out.println(driver.findElements(By.tagName("iframe")).size());
WebElement inputName = driver.findElement(By.xpath("//input[#id='input-applicant.name']"));
inputName.sendKeys("Adam Smith");
html code on ref page
.
Target indeed Page
The expected results are that i can input text to text field, and the actual is that it gives error message:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//input[#id='input-applicant.name']"}
(Session info: chrome=76.0.3809.87)
To achieve the inputName, you must switch the frame two times, please try this code to achieve what you mean :
driver.get("https://www.indeed.com");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("text-input-what")));
WebElement what = driver.findElement(By.id("text-input-what"));
what.sendKeys("Java Programmer");
WebElement where = driver.findElement(By.id("text-input-where"));
for (int i = 0; i < 20; i++) {
where.sendKeys(Keys.BACK_SPACE);
}
where.sendKeys("Jakarta");
WebElement submit = driver.findElement(By.xpath("//button[#class='icl-Button icl-Button--primary icl-Button--md icl-WhatWhere-button']"));
submit.click();
wait.until(ExpectedConditions.elementToBeClickable(By.className("title")));
WebElement thirdElement = driver.findElement(By.className("title"));
thirdElement.click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[contains(text(),'Apply Now')]")));
WebElement apply = driver.findElement(By.xpath("//*[contains(text(),'Apply Now')]"));
apply.click();
driver.manage().window().maximize();
Thread.sleep(1000);
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("[src^='https://apply.indeed.com/indeedapply/x'")));
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("[src^='https://apply.indeed.com/indeedapply/resume']")));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#id='input-applicant.name']")));
WebElement inputName = driver.findElement(By.xpath("//input[#id='input-applicant.name']"));
inputName.sendKeys("Adam Smith");
Thread.sleep(2000);

How to click more options in Compose sections using Selenium?

I am practising coding on Selenium Java.
I click on compose section and entered To,Subject and Body and trying to click on the dotted lines to select label as Social but unable to click on the section.
Please find the below code.
#Test
public void testSendEmail() throws Exception {
driver.get("https://mail.google.com/");
WebElement userElement = driver.findElement(By.id("identifierId"));
userElement.sendKeys(properties.getProperty("username"));
driver.findElement(By.id("identifierNext")).click();
Thread.sleep(1000);
WebElement passwordElement = driver.findElement(By.name("password"));
passwordElement.sendKeys(properties.getProperty("password"));
driver.findElement(By.id("passwordNext")).click();
Thread.sleep(1000);
WebElement composeElement = driver.findElement(By.xpath("//div[contains(text(),'Compose')]"));
composeElement.click();
WebDriverWait wait=new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//textarea[#name='to']")));
//To Field
driver.findElement(By.name("to")).clear();
driver.findElement(By.name("to")).sendKeys(String.format("%s#gmail.com", properties.getProperty("username")));
//Subject Field
String emailSubject = properties.getProperty("email.subject");
driver.findElement(By.xpath("//input[#name='subjectbox']")).sendKeys(emailSubject);
//Body
String emailBody = properties.getProperty("email.body");
driver.findElement(By.xpath("//div[#class='Ar Au']//div")).sendKeys(emailBody);
//More options----Line where I am unable to click on the dotted lines to mark label as social.
driver.findElement(By.xpath("//div[#id=':q6']/div[2]")).click();
Thread.sleep(2000);
//Hover on Label
WebElement Label=driver.findElement(By.xpath("(//div[contains(text(),'Label')])[1]"));
WebElement Social=driver.findElement(By.xpath("//div[contains(text(),'Social')]"));
Actions a=new Actions(driver);
a.moveToElement(Label);
Thread.sleep(5000);
a.moveToElement(Social).click().build().perform();
Thread.sleep(5000);
//Click On Send
driver.findElement(By.xpath("//*[#role='button' and text()='Send']")).click();
It is very difficult to answer without seeing the html.
Instead of:
Actions a=new Actions(driver);
a.moveToElement(Label);
Thread.sleep(5000);
a.moveToElement(Social).click().build().perform();
Try this:
a.moveToElement(Label).build().perform();
waitUntil(ExpectedConditions.elementToBeVisible(Social)).click();

Selenium Webdriver: How to wait untill progressbar vanishes and click on the button [duplicate]

I used explicit waits and I have the warning:
org.openqa.selenium.WebDriverException:
Element is not clickable at point (36, 72). Other element would receive
the click: ...
Command duration or timeout: 393 milliseconds
If I use Thread.sleep(2000) I don't receive any warnings.
#Test(dataProvider = "menuData")
public void Main(String btnMenu, String TitleResultPage, String Text) throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.findElement(By.id("navigationPageButton")).click();
try {
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(btnMenu)));
} catch (Exception e) {
System.out.println("Oh");
}
driver.findElement(By.cssSelector(btnMenu)).click();
Assert.assertEquals(driver.findElement(By.cssSelector(TitleResultPage)).getText(), Text);
}
WebDriverException: Element is not clickable at point (x, y)
This is a typical org.openqa.selenium.WebDriverException which extends java.lang.RuntimeException.
The fields of this exception are :
BASE_SUPPORT_URL : protected static final java.lang.String BASE_SUPPORT_URL
DRIVER_INFO : public static final java.lang.String DRIVER_INFO
SESSION_ID : public static final java.lang.String SESSION_ID
About your individual usecase, the error tells it all :
WebDriverException: Element is not clickable at point (x, y). Other element would receive the click
It is clear from your code block that you have defined the wait as WebDriverWait wait = new WebDriverWait(driver, 10); but you are calling the click() method on the element before the ExplicitWait comes into play as in until(ExpectedConditions.elementToBeClickable).
Solution
The error Element is not clickable at point (x, y) can arise from different factors. You can address them by either of the following procedures:
1. Element not getting clicked due to JavaScript or AJAX calls present
Try to use Actions Class:
WebElement element = driver.findElement(By.id("navigationPageButton"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();
2. Element not getting clicked as it is not within Viewport
Try to use JavascriptExecutor to bring the element within the Viewport:
WebElement myelement = driver.findElement(By.id("navigationPageButton"));
JavascriptExecutor jse2 = (JavascriptExecutor)driver;
jse2.executeScript("arguments[0].scrollIntoView()", myelement);
3. The page is getting refreshed before the element gets clickable.
In this case induce ExplicitWait i.e WebDriverWait as mentioned in point 4.
4. Element is present in the DOM but not clickable.
In this case induce ExplicitWait with ExpectedConditions set to elementToBeClickable for the element to be clickable:
WebDriverWait wait2 = new WebDriverWait(driver, 10);
wait2.until(ExpectedConditions.elementToBeClickable(By.id("navigationPageButton")));
5. Element is present but having temporary Overlay.
In this case, induce ExplicitWait with ExpectedConditions set to invisibilityOfElementLocated for the Overlay to be invisible.
WebDriverWait wait3 = new WebDriverWait(driver, 10);
wait3.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("ele_to_inv")));
6. Element is present but having permanent Overlay.
Use JavascriptExecutor to send the click directly on the element.
WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
In case you need to use it with Javascript
We can use arguments[0].click() to simulate click operation.
var element = element(by.linkText('webdriverjs'));
browser.executeScript("arguments[0].click()",element);
I ran into this error while trying to click some element (or its overlay, I didn't care), and the other answers didn't work for me. I fixed it by using the elementFromPoint DOM API to find the element that Selenium wanted me to click on instead:
element_i_care_about = something()
loc = element_i_care_about.location
element_to_click = driver.execute_script(
"return document.elementFromPoint(arguments[0], arguments[1]);",
loc['x'],
loc['y'])
element_to_click.click()
I've also had situations where an element was moving, for example because an element above it on the page was doing an animated expand or collapse. In that case, this Expected Condition class helped. You give it the elements that are animated, not the ones you want to click. This version only works for jQuery animations.
class elements_not_to_be_animated(object):
def __init__(self, locator):
self.locator = locator
def __call__(self, driver):
try:
elements = EC._find_elements(driver, self.locator)
# :animated is an artificial jQuery selector for things that are
# currently animated by jQuery.
return driver.execute_script(
'return !jQuery(arguments[0]).filter(":animated").length;',
elements)
except StaleElementReferenceException:
return False
You can try
WebElement navigationPageButton = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("navigationPageButton")));
navigationPageButton.click();
Scrolling the page to the near by point mentioned in the exception did the trick for me. Below is code snippet:
$wd_host = 'http://localhost:4444/wd/hub';
$capabilities =
[
\WebDriverCapabilityType::BROWSER_NAME => 'chrome',
\WebDriverCapabilityType::PROXY => [
'proxyType' => 'manual',
'httpProxy' => PROXY_DOMAIN.':'.PROXY_PORT,
'sslProxy' => PROXY_DOMAIN.':'.PROXY_PORT,
'noProxy' => PROXY_EXCEPTION // to run locally
],
];
$webDriver = \RemoteWebDriver::create($wd_host, $capabilities, 250000, 250000);
...........
...........
// Wait for 3 seconds
$webDriver->wait(3);
// Scrolls the page vertically by 70 pixels
$webDriver->executeScript("window.scrollTo(0, 70);");
NOTE: I use Facebook php webdriver
If element is not clickable and overlay issue is ocuring we use arguments[0].click().
WebElement ele = driver.findElement(By.xpath("//div[#class='input-group-btn']/input"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
The best solution is to override the click functionality:
public void _click(WebElement element){
boolean flag = false;
while(true) {
try{
element.click();
flag=true;
}
catch (Exception e){
flag = false;
}
if(flag)
{
try{
element.click();
}
catch (Exception e){
System.out.printf("Element: " +element+ " has beed clicked, Selenium exception triggered: " + e.getMessage());
}
break;
}
}
}
In C#, I had problem with checking RadioButton,
and this worked for me:
driver.ExecuteJavaScript("arguments[0].checked=true", radio);
Can try with below code
WebDriverWait wait = new WebDriverWait(driver, 30);
Pass other element would receive the click:<a class="navbar-brand" href="#"></a>
boolean invisiable = wait.until(ExpectedConditions
.invisibilityOfElementLocated(By.xpath("//div[#class='navbar-brand']")));
Pass clickable button id as shown below
if (invisiable) {
WebElement ele = driver.findElement(By.xpath("//div[#id='button']");
ele.click();
}

Condition for incorrect password selenium java

My code. I enter my login and password in the "userId" and "password" fields. And I would like to write a condition that will check when you hit the "Submit" button or it is possible to login to the system. If "userId" and "password" are correct, then when you press the "Submit" button a new page loads and the next part of the code is posted. But I would like to add a condition when the user gives a bad password. Then, after pressing the "Submit" button, the message "Bad login information" appears on the page. Can anyone help me write such a condition?
for(int i =0;i<userName.size();i++){
driver.findElement(By.id("userId")).sendKeys(userName.get(i));
Thread.sleep(6000);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
driver.findElement(By.id("password")).sendKeys(password.get(i));
Thread.sleep(6000);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
driver.findElement(By.id("Submit")).click();
// Here load new page
// change password
driver.findElement(By.xpath(".//*[#id='_id9']/table/tbody/tr[2]/td[1]/table[1]/tbody/tr[5]/td[2]/a")).click();
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
Thread.sleep(6000);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
// new password
String pwd = RandomStringUtils.random( 15, upper+smaller+number+character);
System.out.println("New password: " + pwd);
driver.findElement(By.id("newPassword")).sendKeys(pwd);
Thread.sleep(6000);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
// confirm password
driver.findElement(By.id("confirmPassword")).sendKeys(pwd);
System.out.println("Confirm password: " + pwd);
Thread.sleep(10000);
driver.manage().timeouts().implicitlyWait(100, TimeUnit.SECONDS);
Try following:
after clicking Submit button; you can check whether this element is present on your page or not : driver.findElement(By.xpath(".//*[#id='_id9']/table/tbody/tr[2]/td[1]/table[1]/tbody/tr[5]/td[2]/a"));
if it is that means new page was loaded as login was successful or else it was a bad login.
you can do so after clicking submit button try following:
UPDATE
List<WebElement> myElemnt = driver.findElements(By.xpath(".//*[#id='_id9']/table/tbody/tr[2]/td[1]/table[1]/tbody/tr[5]/td[2]/a"));
loginSuccessful(myElemnt);
// implementation of loginSuccessful() function:
public boolean loginSuccessful(WebElement element){
try{
element;
return true;
}
catch(Exception e){
System.out.println("Bad Login Information!!");
return false;
}
}
OLD
String beforeTitle = driver.getTitle();
//put your Click Submit Button code here
String afterTitle = driver.getTitle();
if(beforeTitle.equals(afterTitle)){
System.out.println("Bad Login Information!!");
}

Click on button until alert is present in Selenium

I want to click a button until a javascript alert is present.
Here is what I would like to do:
while(!ExpectedConditions.alertIsPresent())
button.click();
But this does not work as the expression is not evaluated to a boolean condition.
I have tried:
while(ExpectedConditions.alertIsPresent() == null)
button.click();
But this results in never going into the loop. Thanks for any guidance
The predicate ExpectedConditions.alertIsPresent cannot be evaluated directly in a while.
You can use it with a waiter:
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.alertIsPresent());
But in your case a better choice would be to implement a predicate that clicks on the button until the alert is present:
WebElement button = driver.findElement(By.id("..."));
// clicks on the button every 100ms until the alert is present
Alert alert = new WebDriverWait(driver, 20, 100).until((WebDriver drv)->{
try{
button.click();
return drv.switchTo().alert();
}catch(NoAlertPresentException ex){
return null;
}
});
// accept the alert
alert.accept();
You can go with this workaround:-
while(alert.getClass().getCanonicalName().toString().equals("org.openqa.selenium.remote.RemoteWebDriver.RemoteAlert")){
button.click();
}

Categories

Resources