Executing a Javascript button click in Selenium without an ID using Java

Currently, I am in the process of setting up a Java program integrated with Selenium automation tool.

Upon the initiation of the program, a Chrome extension that is crucial for its functionality loads alongside the Chrome browser instance.

Following this, Chrome is expected to navigate to a specific webpage, select various elements on the page, and ultimately click a button that appears due to the presence of the extension.

The challenge arises when attempting to interact with this button, as it is dynamically generated by Javascript and lacks any identifiable ID attribute.

Upon inspecting the element, the following HTML snippet is revealed:

<a href="javascript:void(0);" class="selected button-task" 
style="width: 140px; margin-left: 5px; height: 23px;">
<img src="websiteimage.png here" width="20px">Selected Task</a>

Unlike other clickable elements within the page that have distinctive types or IDs, this particular button does not. Nevertheless, interacting with it is crucial for the program's success. How should I proceed?

Upon attempting to locate and click the button using XPath, an error message is encountered:

Exception in thread "main" org.openqa.selenium.InvalidSelectorException: invalid selector: 
Unable to locate an element with the xpath expression //a[contains@class,'selected'] and contains(@class, 'repost-selected button-task') and contains(text(), 'Repost Selected') because of the following error:

SyntaxError: Failed to execute 'evaluate' on 'Document': 
The string '//a[contains@class,'selected'] and contains(@class, 'repost-selected button-task') and contains(text(), 'Repost Selected')' is not a valid XPath expression.

I would greatly appreciate any guidance or suggestions on how to effectively handle this situation. Thank you!

Answer №1

It's crucial that I press this button. What steps should I take?

To click the button, consider the following methods:

WebDriverWait wait = new WebDriverWait(driver,10);
  • Using By.cssSelector():

    wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("a.selected.button-task"))).click();
    
  • Using By.linkText():

    wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Selected Task"))).click();
    
  • Using By.partialLinkText():

    wait.until(ExpectedConditions.elementToBeClickable(By.partialLinkText("Selected Task"))).click();
    
  • Using By.xpath():

    wait.until(ExpectedConditions.elementToBeClickable(By.xpath(".//a[normalize-space()='Selected Task']"))).click();
    

Answer №2

Give this a shot:

driver.findElement(By.xpath("//a[contains@class,'selected'] and contains(@class, 'button-task') and contains(text(), 'Selected Task')")).click()

Answer №3

I managed to crack the code with this solution:

WebElement extensionBox = driver.findElement(By.xpath(".//a[normalize-space()='Selected Task']"));

Actions actionsTwo = new Actions(driver);
JavascriptExecutor jseTwo = (JavascriptExecutor) driver;
actionsTwo.moveToElement(extensionBox).click();
jseTwo.executeScript("arguments[0].click()", extensionBox);

Previous solutions fell short either because they couldn't locate the object on the page or led to compiling errors.

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

React components function similar to objects in object-oriented programming

When creating a React component, I used React.createClass() method. module.exports = React.createClass({ // input-field-units.jsx file is where this code resides displayName: 'input-field-units', render: function () { return ( ...

Learn the process of transforming a filter into a directive in AngularJS

Here is a question I asked previously, where I was looking to remove negative numbers from an input field: <input type = "text" ng-model="number"></input> In that previous question, Paritosh provided me with a helpful solution, but now I am i ...

Display the elements of a div at a reduced size of 25% from its original dimensions

I'm currently developing a JavaScript-based iOS simulator that allows users to view their created content on an iPhone and iPad. This involves using AJAX to load the content/page into the simulator, but one issue is that the simulator isn't life- ...

How can I adjust the positioning of labels in Semantic UI React?

Has anyone successfully changed the label position from right side to left? I attempted using float: left but it didn't have any effect. import {Radio } from "semantic-ui-react" <Radio label="in progress" toggle /> https://i.sstatic.net/hNGb6. ...

Receiving a blank response instead of the expected text

I have been attempting to scrape only the titles of all the links on a website using the code below. However, I am only receiving empty strings as output. String url = "https://www.linkedin.com/learning/learning-azure-sql-querying-18952522?trk=learnin ...

Enhanced Security Patches for OpenJDK Versions 8 and Above Now Available

There was a discussion where it was mentioned that under Oracle's new licensing policy, you can only choose two out of Stable, Secure, Free. This implies that if you opt for Stable and Secure, you cannot have it for Free, requiring the use of Oracle J ...

`Center the image on top of the text`

Currently, I am working with Bootstrap 4 to create a component that includes two tiles. Each tile has an icon image on the left side and a hyperlink on the right side. On desktop view, the tiles should be displayed horizontally and vertically centered. How ...

The issue with ngFileUpload causing empty file posts on Safari

Currently, I am utilizing ngFileUpload to transmit images to the Cloudinary service. My application is constructed on Ionic and is meant to be functional on both iOS and Android platforms. The code snippet below showcases my image uploading process: .se ...

Extract information from a webpage using JavaScript through the R programming language

Having just started learning about web scraping in R, I've encountered an issue with websites that utilize javascript. My attempt to scrape data from a specific webpage has been unsuccessful due to the presence of javascript links blocking access to t ...

Detecting Duplicates in an Angular JS Repeater and Handling the Not Allowed Exception

I am working on a task where I need to ensure that the object being added to an array of objects is not already present in a temporary array of objects. While using AngularJS, I encountered an error stating "Duplicates in a repeater are not allowed." This ...

Navigating through various div elements in Javascript and sending parameters to a script

Context In my project, I am using PHP to generate a series of voting sections. Each section follows the same format except for a unique number assigned to it, which increases with each iteration of the PHP loop. To keep track of the unique numbers, I uti ...

AngularJS: Modifying the parent scope from a controller inside an ng-switch

I've noticed that I can change a model value from a child controller, but when the child controller is inside an ng-switch, this functionality doesn't seem to work. Why is that? To illustrate this issue, I have created an example. One workaround ...

Guide on how to retrieve the vertex information once an object is loaded using the ObjLoader in Three.js

When using ObjLoader in Three.js to load a *.obj file into my scene, everything works fine. However, I'm uncertain on how to manipulate the object's vertices and indices individually. How can I access the vertices of the loaded *.obj model? Atte ...

An arrow function fails to activate

Here is the code snippet that I am dealing with: class App extends React.Component { loginComponent = <button onClick={this.signUp}>Sign Up</button>; signUp = () => { alert("test"); } rende ...

Creating HTML content in TypeScript with NativeScript using document.write()

Essentially, I am looking to create a set number of labels at various row and column positions depending on the user's input. However, I have been unable to find any resources that explain how to write to the .component.html file from the .component.t ...

An error has occurred as the Chrome binary could not be located. Please raise the exception class with the message, screen, and stack trace to resolve this issue

Using the selenium library, we can control web browsers programmatically. In this code snippet, we first import the necessary modules using statements like from selenium.webdriver.common.keys import Keys. We also set a variable called "PATH" to store the ...

Performing operations in Selenium on Firefox

I've been attempting to execute the actions operation on Firefox Quantum version 57+ with Selenium version 3.5.0 and geckodriver 0.19.1. Unfortunately, it seems unable to perform the click operation using Actions. Here's the code I've writt ...

What is the best way to initiate Selenium with Chrome driver while retaining all current browser cookies?

My current understanding is that Chrome Driver always begins without any stored browser cookies. I am looking for a way to have the driver start with all the cookies saved by Chrome. Is there a method to initiate the driver with the existing cookies? I a ...

Cleaning a string of word characters in Javascript: a step-by-step guide

I have been working on cleaning strings that were transformed from word text, but I am facing an issue with removing the special character '…' When I click on the "clean" button, the script currently removes all dots and only one special ...

Observing nested data changes in Vue.JS?

In my Vue.js components, I have a group of checkboxes that are sending data to the parent element. My goal is to monitor this data for changes and use it to filter information in an API call. When certain checkboxes are selected, the data stored on the pa ...