What is the Java method for clicking on an image button in WebDriver?

After entering all the required data and clicking on the Apply Now button, it is not saving. However, when attempting to create it manually, the process completes in less than 15 seconds.

Attached is a screenshot for reference.

Here is the relevant HTML code:

//Navigating to Quick Application
driver.get(QAurl);
Thread.sleep(15000);
driver.findElement(By.id("DdlSalesPerson")).sendKeys("Swamy m Kumara");
driver.findElement(By.id("TxtFName")).sendKeys("Kumar");
driver.findElement(By.id("TxtLName")).sendKeys("Swamy");
driver.findElement(By.id("TxtAddress")).sendKeys("434, Main Road, Somajiguda");
driver.findElement(By.id("TxtZip")).sendKeys("79081");
driver.findElement(By.id("TxtSSN1")).sendKeys("881");
Thread.sleep(15000);
driver.findElement(By.id("TxtSSN2")).sendKeys("72");
driver.findElement(By.id("TxtSSN3")).sendKeys("4365");
Thread.sleep(5000);
driver.findElement(By.id("TxtDayPhone1")).sendKeys("963");
driver.findElement(By.id("TxtDayPhone2")).sendKeys("210");
driver.findElement(By.id("TxtDayPhone3")).sendKeys("5478");
Thread.sleep(5000);
driver.findElement(By.id("ChkIAgree")).click();
driver.findElement(By.id("TxtSignature")).sendKeys("Kumar Swamy");
Thread.sleep(5000);
System.out.println("Entered all the required fields");
//Reading the value in the image.
WebElement element = driver.findElement(By.id(OR.getProperty("FP_SImg_ID")));
String src = ((JavascriptExecutor)driver).executeScript("return arguments[0].attributes['src'].value;", element).toString();
img =src.split("=");
System.out.println("Value retrieved from the Image source: "+img[1]);
driver.findElement(By.id(OR.getProperty("FP_TxtSImg_ID"))).sendKeys(img[1]);
Thread.sleep(5000);
driver.findElement(By.id("TxtEmailId")).sendKeys("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d6d5d4f7d6d5d499d4d8da">[email protected]</a>");
driver.findElement(By.name("BtnSubmit")).click();
Thread.sleep(35000);
System.out.println("Successfully Applied from the QuickApp");

HTML code for the Apply now button:

<input id="BtnSubmit" type="image" style="height:33px;width:121px;border-width:0px;" 
onclick="javascript:return validateControls();" src="../Common/Images/HybridQA  
/apply_now.png" title="Submit Here" tabindex="45" name="BtnSubmit">

If you have any suggestions or solutions, please share. Your help is greatly appreciated.

Answer №1

Your code contains 1 minute and 25 seconds of Thread.sleep()...

If you are waiting for elements to appear, remove all instances of thread.sleep() and instead use an explicit wait:

http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp

Refer to the example below from the linked page:

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));

Check out the ExpectedConditions class for available conditions in Selenium. If they don't suit your needs, you can easily write your own expected conditions.

-------------------Edit-------------------

Just to clarify, this answer pertains to the original question quoted below (you can view the edit history of the original question as well):

Taking long time to save after clicking on Apply Now button using Webdriver in Java

Taking long time to save after clicking on Apply Now button using Webdriver in Java. I have entered all the data and clicked on Apply now button, it is not at all saving. But when i try to create it manually, it is saved in less than 15 seconds. Please find the attached screen shot.

Answer №2

There are two possible explanations for this issue.

  1. The first reason could be related to the HTML code of the 'Apply Now' button. In the code, it is identified as "input id='BtnSubmit'", but in your script, it is written as 'driver.findElement(By.name("BtnSubmit")).click();'. It should actually be 'driver.findElement(By.id("BtnSubmit")).click()', where 'name' should be replaced with 'id'.

  2. Another possibility is that after clicking the 'BtnSubmit' button at the end of the script, the session might expire immediately. This problem commonly occurs when using a combination of an older and newer version of the Selenium standalone jar file. Make sure to only use the latest version of the Selenium jar file and avoid mixing it with older versions.

Answer №3

Implement this method:

driver.findElement(By.id("TxtEmailId")).sendKeys(Keys.ENTER);

Then add the following line:

driver.findElement(By.id("TxtEmailId")).sendKeys("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="55343736153437367b363a38">[email protected]</a>");

Lastly, include a comment:

//driver.findElement(By.name("BtnSubmit")).click();

Your updated code should resemble this:

driver.findElement(By.id("TxtEmailId")).sendKeys("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d7c7f7e5d7c7f7e337e7270">[email protected]</a>");
driver.findElement(By.id("TxtEmailId")).sendKeys(Keys.ENTER);
//driver.findElement(By.name("BtnSubmit")).click();

Dealing with image buttons can be tricky because they require all fields to be completed. Make sure you've filled out all mandatory fields and hit enter after the last input. Try it manually first. Instead of clicking the button, press enter in the final input field and apply the same approach in automation.

Update:

Substitute your own code and replace Thread.sleep() with the method below.

Call it like so:

waitForElementToBePresent(By.id("DdlSalesPerson"), 15000);

This function waits for the next element specified as an argument. It returns true if found, false if not. If the element is located within the given time frame, it will immediately return true without waiting further.

public boolean waitForElementToBePresent(By by, int waitInMilliSeconds) throws Exception
    {
        WebDriver driver = getDriver();
        int wait = waitInMilliSeconds; 
        int iterations  = (wait/250); 
        long startmilliSec = System.currentTimeMillis(); 
        for (int i = 0; i < iterations; i++) 
        { 
            if((System.currentTimeMillis()-startmilliSec)>wait) 
                return false; 
            List<WebElement> elements = driver.findElements(by); 
            if (elements != null && elements.size() > 0) 
                return true; 
            Thread.sleep(250); 
        } 
        return false; 
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Designate categories by utilizing the x-amz-tagging request header

I'm in the process of creating a Node program to upload files to aws s3, and I'm having trouble figuring out how to specify the x-amz-tagging with the request header. I attempted a solution, but it's not working as expected! function crea ...

Issue with child component mounted before parent component creation

I have encountered an issue in my Vue application. It seems that the child component's mounted function is being executed before the parent component's created function. I am passing props from the parent component to the child component and I w ...

Learning how to rotate a cube mid-air with three.js

Currently, I am utilizing the three.js framework along with physi.js for implementing forces and gravity in my project. The issue I am encountering involves positioning a dice on a plane and then being able to launch or flip it from that position with a sp ...

Send the user to a specified destination

Currently, I am working on creating a form that allows users to input a location and have the page redirect to that location after submission. However, I am facing difficulty in determining how to set the value for action="" when I do not know what the loc ...

transforming a text input into unadorned plain text

Currently, I am in the process of creating a small HTML form that consists of a single textbox input. Once the user enters text into this textbox and clicks on a button located at the end of the page, I would like the textbox to transform into normal plain ...

Inquiries regarding the distinctive key and component framework of Ant Design

Currently, I am in the midst of a project utilizing react, next.js, and antd. However, an error message has popped up stating: Warning: Each child in a list should have a unique "key" prop. This issue precisely stems from the absence of a uniqu ...

When using PHP to echo buttons, only the value of the last echoed button will be returned in JavaScript

I am encountering an issue when trying to define a dynamic var for button value in my JavaScript code. Despite it working in PHP, the same code does not seem to function properly in JavaScript. Imagine I have three buttons echoed using PHP with values 1, ...

Tips for resolving issues with mysql_fetch_assoc()

Similar Question: mysql_fetch_array() error - Fixing parameter issue Whenever I execute the code below, I encounter this issue: Warning: mysql_fetch_assoc(): provided argument is not a valid MySQL result resource If anyone knows how to rectify this pro ...

Changing a string by alternating between uppercase and lowercase letters for each character

I'm currently working on a project to develop a program that takes a basic password and transforms it into a more intricate one by changing certain characters to special symbols (e.g., s to $). I have successfully achieved this functionality, but now ...

How can I transfer an array of objects obtained from an ajax call to an observable array?

One of my functions involves making an ajax call and receiving data in the callback. It looks something like this: function fetchData(callback) { //perform ajax if(callback) { callback(data.data); } } If I use the function like this: fetc ...

What are some ways to display unprocessed image data on a website using JavaScript?

I have an API endpoint that provides image files in raw data format. How can I display this image data on a website using the img tag or CSS background-image property, without utilizing canvas? One possible approach is shown below: $.get({ url: '/ ...

Retrieve the canvas coordinates for the images starting at lx and ending at rx on the x-axis, and

Currently, I am working on a project where I need to implement a drag and drop feature for an image within a PDF document. The goal is to retrieve the coordinates of the dragged image and use them later for document signing. The situation I am dealing wit ...

Detecting a palindrome using recursive method in the Java programming language

Can anyone help me understand the recursive method used to determine if a word is a palindrome? public static boolean isPalindrome(String word) { if (word.length() == 0 || word.length() == 1) { return true; } else if (word.charAt(0) == wo ...

Load CKEditor.js with RequireJS following the textarea element

If you need a WYSIWYG editor, CKEditor could be the answer. Check out their documentation here. To properly load CKEditor, make sure to add the following script tag in the header: <script src="../ckeditor/ckeditor.js"></script> ... Then, inc ...

javascript - The onmessage event will not trigger when using a Java server

I have encountered an issue with my Java server and JavaScript websocket client. Despite trying various solutions from this site, I am still unable to resolve the problem. So, I decided to share my code here in hopes of getting some assistance. The proble ...

Pause in the Finally clause following the completion of the try block

I have been experimenting with the following concurrency code snippet: import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final Stri ...

Issue with Node.js: Promise not completing execution

My current project involves retrieving data from multiple collections in MongoDB using Node.js and promises. Below is a snippet of the basic code I am using: await Promise.all( ["a", "b", "c"].map(async (collection) =& ...

The custom pagination feature in Addsearch UI always default to displaying the first page of search

I am currently using addsearch-ui version 0.7.11 for my project. I have been attempting to integrate a customized pagination function based on this example template. However, I have encountered an issue where the arrow buttons always navigate to the first ...

Options for authentication with Spring Boot and Angular version 2 or 4

As I prepare to integrate user authentication in my app, I realize this is my first time working on an Angular + Spring project. I am interested in learning about the various options available for authentication. While I don't need a step-by-step guid ...

Creating clickable div elements within a loop

In the .JS file I have the function below (which I later call in an HTML file): function writeDiv(){ x = 1 myArray.forEach(item => { htmlText += '<div class="divsArray">'; htmlText += '<h5> Value of X ...