Having trouble locating an element in Selenium Chrome using JavaScript

I'm automating a webpage using JavaScript and selenium, which involves clicking on several buttons. To start off, my code establishes a connection with the existing chrome window in the following way:

var chrome = require("selenium-webdriver/chrome");
    var options = new chrome.Options();
    options.options_["debuggerAddress"] = "127.0.0.1:9222";
    var driver = new webdriver.Builder()
        .forBrowser('chrome')
        .setChromeOptions(options)
        .build();

The driver is functioning correctly and navigates to the correct page. I've confirmed this by having the driver output the page's source code, which aligns with the site's source accessed through the right-click menu.

In addition, I have a function named checkForName(), which takes an XPath as input and returns the element for selenium to interact with

async function checkForName(selector) {
  console.log("Checking for name");
  try {
            const element = await driver.findElement(By.xpath(selector));
            return element;
  } finally {
            console.log("Error: element " + selector + " not found");
            return false;
  }
}

This function is later invoked within the program

element = await checkForName("//button[@class='mBiMV']");
if(element) {
   element.click();
}

However, upon running the program, the following error message appears in the console:

Checking for name
SnapBot-JS.js:18
Error: label //button[@class='mBiMV'] not found

I've double-checked the existence of the button, and the document is fully loaded before the chromedriver connects, leaving me uncertain about what steps to take next

EDIT: Below is the HTML code for the button in question:

<button type="button" class="mBiMV">

Answer №1

The unique identifier, known as classname, which in this case is mBiMV, is generated dynamically and can change at any time. This means that relying on this identifier in locators may not be reliable, as it could change the next time you access the application or during the next startup. Instead, it is recommended to use attributes with static values for more stable identification.


Solution

Based on the provided HTML:

<button type="button" class="mBiMV">

It appears that there are no other attributes with static values assigned, making it challenging to uniquely identify the element using just its class name (mBiMV). In such cases, it is advisable to navigate to a parent element that has a static attribute and then locate the desired element within it. For example:

<div class="foo" id="bar">
    <button type="button" class="mBiMV">
    

An effective locator strategy for the above HTML could involve either of the following approaches:

  • Using css:

    const element = await driver.findElement(By.css("div.foo#bar > button"));
    
  • Using xpath:

    const element = await driver.findElement(By.xpath("//div[@class='foo' and @id='bar']/button"));
    

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

Learning to use jQuery to search and populate the contents of div elements with object data

I'm facing a challenge with inserting the data received from an ajax call. In my HTML code, I have multiple divs with unique IDs: <div id ="first_name"> content </div> <div id ="last_name"> content </div> <div id ="email"& ...

Do the circular dependency warnings in Angular pose a significant issue?

Angular has long supported a showCircularDependencies build flag that identifies circular dependencies within classes. But do these warnings pose a real issue? Let's consider an example. import {MyOtherService} from './my-other-service.ts'; ...

Is there a way to transfer driver information between methods smoothly?

Just started working with Selenium and I have a query. I created a method called urlload to load a specific URL, but when I try to read webElements of the webpage loaded in that method from another class, it doesn't seem to work. Any advice or hel ...

when within a 'for in' loop

Querying Object Equivalence: I find myself struggling to comprehend the flow of my code and how I can rectify it. Within the areEqual function, I am comparing the "value" property of two objects. If they match -> isEqual=true -> continue with the ...

The calculator is spitting out some strange outcomes

My calculator is producing some strange results when I input certain values. I have added it to jsfiddle so you can take a quick look. For example, when I enter 4000 as the principal, set the duration to 1 year, and choose a 1% interest rate, the calculat ...

After reaching a total of 20 entries, req.body will automatically convert the array into an

I have the ability to dynamically add properties to my form: <form action=""> <div class="property"> <label>Name : <input type="text" name="properties[1][name]"></label> <label>Order : <input type="text" na ...

When a URL is triggered via a browser notification in Angular 2, the target component ceases to function properly

Whenever I access a URL by clicking on a browser notification, the functionality of the page seems to stop working. To demonstrate this issue, I have a small project available here: https://github.com/bdwbdv/quickstart Expected behavior: after starting t ...

Adjust the height of the list when including or excluding floated list items that are not in the final row

Within my ul are li elements with varying widths that wrap around inside a container into multiple rows. When removing an li element from the ul, I want the container's height to adjust dynamically in case a row is eliminated. If the removal happens ...

Exploring the function.caller in Node.js

Currently, I have a task that relies on function.caller to verify the authorization of a caller. After reviewing this webpage, it seems that caller is compatible with all major browsers and my unit tests are successful: https://developer.mozilla.org/en-U ...

Implementing a JSON query with an onkeyup event listener

My main objective with this code is to trigger a json query request by using a textfield to specify the location. It's essentially a quick search feature that searches for specific content on a different website. For example, if I input www.calsolum/ ...

Provide the scope to the directive when calling the $uibModal.open method

I am interested in developing a custom directive that displays data based on the scope of its parent controller. Here is the directive's JavaScript code: (function () { 'use strict'; angular .module('blabla') ...

Is there a way to dynamically retrieve a list of sheets from a spreadsheet using the Google Sheets API in a React application?

How can I retrieve a list of all sheets in the Google Sheet below? Take note of the parameter ranges=${sheet}. The current code is set up to fetch data from a single sheet. However, my goal is to create a dynamic call by obtaining a list of all available ...

Is there a way to eliminate preflight requests from the $http header?

//loop through individual logins $rootScope.setting.instances.forEach(function(ins) { var header = { "Accept": "application/json", "Authorization": "Basic " + btoa( ins.uname + ':' ...

jQuery AJAX and PHP can be used together to verify conditions and return either

Is there a way to determine whether a PHP script returned true or false using jQuery AJAX? My current ajax call code seems to be working fine, but it always redirects to the profile page even if the login was unsuccessful... $("#signInForm").submit(func ...

Choose the Enum in a dynamic manner

I have three enums Country_INDIA, Country_USA,Country_AUSTRALIA. During runtime, the specific country name is determined (it could be either INDIA, USA, or AUSTRALIA). Is it possible to select the correct enum based on the country name at runtime? For in ...

Incorporating an NPM module into a React file: Webpack encounters resolution issues

After reviewing information from this source and here, the process of publishing a react module to NPM and then using it in another project while having the component in the node_modules directory should be as follows: Create and export a module Specify ...

Guide on accessing a local image while setting the background image using JavaScript

I am trying to set a background image from a local source on my computer. Below are two lines of code, one that works and one that does not: (the local one fails) _html.style.backgroundImage = 'url("urlsourceblahblahblah")'; _html.style.backgro ...

Load HTML/erb templates efficiently in Rails to optimize performance for AngularJS applications

I recently came across a discussion about eager loading HAML templates on this website. The concept of caching HTML partials to enhance performance in Angular applications caught my attention. However, I'm curious to know if there is a similar approac ...

Executing a Select Change in a React Application using CasperJS

Has anyone else encountered difficulties with this issue? I have a basic React page set up, with a simple component that renders a select element and triggers a callback function when the value changes. Here is the basic structure of the component: const ...

What is the method for creating a regex pattern that captures a single symbol under specific conditions?

I am in need of a JavaScript regex that can specifically select a single character with one condition: it must not be followed or preceded by a particular specified character. The target character is /, but I want to select it only if it is not immediatel ...