A guide to automating button clicks in tests with Selenium and Java

I am currently automating a test using Selenium and I am attempting to click a button using xpath. Here is the snippet of my code:

WebElement LogInButton = driver.findElement(By.xpath("/login"));
LogInButton.click();

Unfortunately, when running this code, I encounter an error message that reads:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"/login"}

The only information I have about the button is as follows:

<a href="/login">Login</a>

Along with the URL it redirects to. What could be the issue with my xpath reference? How should I correctly identify this button? Any assistance would be greatly appreciated. Thank you.

Answer №1

If you want to trigger a click event on an element, there are several Locator Strategies you can utilize:

  • Using linkText:

    driver.findElement(By.linkText("Login")).click();
    
  • Using cssSelector:

    driver.findElement(By.cssSelector("a[href='/login']")).click();
    
  • Using xpath:

    driver.findElement(By.xpath("//a[@href='/login' and text()='Login']")).click();
    

Key recommendations

When invoking the click() method, it is advisable to employ WebDriverWait for elementToBeClickable() using one of the following Locator Strategies:

  • Using linkText:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Login"))).click();
    
  • Using cssSelector:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href='/login']"))).click();
    
  • Using xpath:

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//a[@href='/login' and text()='Login']"))).click();
    

Further Reading

You may find additional valuable insights in the following discussions:

  • NoSuchElementException, Selenium unable to locate element
  • Exception in thread “main” org.openqa.selenium.NoSuchElementException: Unable to locate element: //*[@id='login-email']

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

Update the content within every <td> element using AJAX/JQUERY on a table created from JSP

I have a database filled with descriptions and corresponding ID numbers. The table displays them like this: index.jsp <table> <tr> <td>Name:</td> <td>Id:</td> </tr> <c:forEach items ...

How can I use Selenium webdriver to ensure it waits for an element to update its attribute to a different value in Java?

Here is the element I am working with: String sId = driver.findElement(By.xpath(path)).getAttribute("data-id"); Now that the attribute value is stored in "sId", my goal is to instruct Selenium to wait until the data-id attribute value is NOT equal to sID ...

I am working on creating an automated system for a website using Selenium WebDriver. Strangely, the xpath is showing up as underlined. Does anyone have any insight into why

Hey everyone, I am facing a minor issue while trying to automate a daily questionnaire. I was following a tutorial on YouTube and at around the 5:50 mark, the instructor copied an xpath code and pasted it on the side. But when I tried the same, my code got ...

Utilizing properties files to pass values in Cucumber feature files' data tables

I am looking to retrieve the values of variables in a datatable from feature files using a properties file. I have attempted to implement this, but encountered an error. The complete stack trace is provided below. org.openqa.selenium.WebDriverException: u ...

First-character styling not applying to ID in CSS

My CSS :first-letter selector is effective on all p elements, however when applied to a span with the id #fletter, it doesn't seem to work... #fletter span:first-letter { font-weight: 600; font-size: 25px; } <span id="fletter"> The : ...

Guide on maintaining Spring Security authentication across Angular front-end

Following the initial feedback on my query, I made adjustments to my Spring Security setup and successfully logged in and accessed a test endpoint using Postman. However, when the same endpoint is called by Angular post successful login, the request fails, ...

I am encountering the org.json.JSONException error message stating that there is no value for a specific item in my JSON array

Despite having "feels_like" in my JSON array, the error log is indicating that it is not present. CODE: protected void onPostExecute(String s) { super.onPostExecute(s); try { JSONObject jsonObject = new JSONObject(s); ...

Exploring the possibilities of utilizing Selenium variables in Python 3 to automate email creation

Hi there! This is my first post and I'm fairly new to Python, especially when it comes to sending emails from it. My current objective is to scrape the first 5 articles from a website and send them to my email address. Right now, all I need is for it ...

Using the Selenium web driver with Google Chrome

I'm having an issue while attempting to utilize Selenium WebDriver with Google Chrome in Eclipse. When I execute my code, the following error is displayed: Starting ChromeDriver 2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed) on port 40315 ...

An error occurred in the cucumber StepDefinitions feature, specifically a java.lang.NullPointerException

I encountered a NullPointerException error while working on the Login action feature: Feature: Login action Scenario: Successful Login with Valid Credentials # C:/Users/chaitanya/workspace/cucumber2/src/feature/myfeature.feature:3 Given User is on Home ...

How to use XPath in Python to extract and separate text from a href within the same td element

My webpage contains HTML code similar to this: <tr><td style="text-align:center;">7</td><td class="multi_row" style="line-height:15px;">Loaded on 'NYK LEO 303W' at Port of Loading<br> <a href="JavaScript:void(0); ...

Is it possible to execute selenium tests without utilizing the Webdriver interface in your codebase?

Recently, I experimented with running a Selenium test without utilizing the Webdriver interface in my code. Surprisingly, the code performed as expected without encountering any issues. System.setProperty("webdriver.chrome.driver", "C://Java learning//Sel ...

Using Selenium in Python to choose an option from a dropdown menu within a <div> element

Currently facing a challenge here! I am trying to pick an item from the 'All reviews' drop down but it does not behave like a typical menu where I can select each item individually and then click on it. Instead, the drop down functions as an ele ...

When writing to a PHP socket followed by reading, the socket becomes blocked

One issue I am facing is having a Java server listening to requests while a PHP page is sending those requests. After connecting to the server, I use the "socket_write" command to send something, and then attempt to read the server's response with "s ...

Unable to retrieve the textual content from an anchor tag

How can I retrieve the text value of a link with "My account" as the anchor text? I'm looking to verify if I am logged in to a website by checking this specific string. I've been struggling to find the correct approach, despite trying various m ...

Choosing a value from a dropdown menu with Selenium and Python: Step-by-step guide

Currently, I am using Selenium with Python and I am looking to automate the process of selecting an option from a drop-down menu. Specifically, I need to select the option labeled (00:00-06:00). <div class="prepopulated-select__SelectContainer-sc-xyh ...

Receiving NullReferenceException when attempting to access Firefox logs with Selenium in c#

I am currently working on a project that involves recording log files in Firefox using Selenium with c#. To test this functionality, I have created a basic example to open a browser and retrieve the logs. However, I encountered an issue with a 'Obje ...

The ChromeDriver detects when the Chrome browser is launched

When attempting to use selenium chromedriver in Python for the website www.mouser.co.uk, it is immediately flagged as a bot. Does anyone have an explanation for this? Below is the code I am utilizing: https://i.stack.imgur.com/g3uLP.png options = Options ...

The ngModel in Angular 2 does not update when a selection is made

Two select options are available, where the second one is dependent on the first: <div class="form-group"> <label class="col-xs-12 col-sm-2 control-label">Vehicle Type:</label> <div class="col-xs-12 col-sm-10"> ...

Unable to "clean up" the HTML document

Struggling with utilizing tidy to produce clean html code. My attempt looks like this: tidy -i -utf8 output/page_1530597755.html -b -o test.html However, no output file is being created! Instead, there are numerous warnings and an error message popping u ...