Element Not Found Error: Element could not be located - Script using JavaScript with Seleniumwebdriver

After extensive research, I have identified the issue at hand. The challenge lies in the fact that others do not follow the same coding structure as me and are unclear about where or what to insert into my code. I am aware that a try/catch statement or the wait.until statement is required. Despite trying both approaches without success, I would greatly appreciate any assistance. Thank you in advance!

require('chromedriver');
const selenium = require("selenium-webdriver");
const By = selenium.By;
const until = selenium.until;

const driver = new selenium.Builder().forBrowser("chrome").build();

driver.get("https://qa.chaplinq.org/LinQ/Account/SignIn");

const locators = {
    loginForm: By.id("login-form"),
    loginField: By.css("input#UserName"),
    loginPass: By.css("#login-form input[name='Password']"),
    signIn: By.css("form#login-form > footer > button"),
    createAcc: By.css("a#createAccountBtn"),
    applyfirstName: By.css("input#FirstName"),
    applylastName: By.css("input#LastName"),

function createAcc() {
    driver.findElement(locators.createAcc).click();
};

function firstName(text) {
    driver.findElement(locators.applyfirstName).sendKeys(text);
};

createAcc();
firstName("kevin");

[ERROR] node : (node:1896) UnhandledPromiseRejectionWarning: 
NoSuchElementError: no such element: Unable to 
[ERROR] locate element: {"method":"css 
selector","selector":"input#FirstName"}
[ERROR] At line:1 char:1
[ERROR] + node index.js
[ERROR] + ~~~~~~~~~~~~~
[ERROR]     + CategoryInfo          : NotSpecified: ((node:1896) 
Unh...put#FirstName"}:String) [], RemoteExcepti 
[ERROR]    on
[ERROR]     + FullyQualifiedErrorId : NativeCommandError
[ERROR]  
[ERROR]   (Session info: chrome=69.0.3497.100)
[ERROR]   (Driver info: chromedriver=2.42.591088 
(7b2b2dca23cca0862f674758c9a3933e685c27d5),platform=Windows NT 
[ERROR] 10.0.17763 x86_64)
[ERROR]     at Object.checkLegacyResponse 
(C:\users\kevin.yu\node_modules\selenium-webdriver\lib\error.js:585:15)
[ERROR]     at parseHttpResponse (C:\users\kevin.yu\node_modules\selenium- 
webdriver\lib\http.js:533:13)
[ERROR]     at Executor.execute (C:\users\kevin.yu\node_modules\selenium- 
webdriver\lib\http.js:468:26)
[ERROR]     at process._tickCallback (internal/process/next_tick.js:68:7)
[ERROR] 
[ERROR] (node:1896) UnhandledPromiseRejectionWarning: Unhandled promise 
rejection. This error originated either 
[ERROR] by throwing inside of an async function without a catch block, or by 
rejecting a promise which was not 
[ERROR] handled with .catch(). (rejection id: 1)
[ERROR] 
[ERROR] (node:1896) [DEP0018] DeprecationWarning: Unhandled promise 
rejections are deprecated. In the future, 
[ERROR] promise rejections that are not handled will terminate the Node.js 
process with a non-zero exit code.
[ERROR] 

Answer №1

The error message "NoSuchElementError" indicates that the specified element is not currently present in the HTML document. This could happen when elements are loaded or removed dynamically on the page. If your Selenium automation scripts are executing faster than the element can be displayed, this error may occur.

Could it be possible that the element input#FirstName only appears after it has been interacted with (e.g., clicked)?

If that's the case, you might want to consider inserting a pause or wait function between the createAcc() and firstName() actions.

Answer №2

Remember to always include a closing brace to end your "locators" object in order to avoid any syntax errors.

Answer №3

Dealing with Web Components and Shadow DOM Elements

An issue arises when attempting to locate elements within shadow DOMs, even if they are present on the page.

The use of the /deep/ and ::shadow css selectors has been phased out and no longer available as a solution.

For those seeking an alternative approach, there is a helpful workaround detailed in this article (not authored by me) which involves utilizing the executeScript function in Java.

Here is a sample javascript code snippet:

For instance, if you have a host/web component tag with id "hostId" on the page, and you need to access an element inside it with id "targetElementId":

async function getComponentElement(hostId,targetElementId){
    let host = await driver.findElement(By.id(hostId));
    let targetElement = await driver.executeScript(() => {            
            return arguments[0].shadowRoot.getElementById(arguments[1]);
        }
        ,host,targetElementId
    );    
    return targetElement ;
}

let element = await getComponentElement('hostId','targetElementId');

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

Securing your Node.js connect-rest REST API with OAuth: A comprehensive guide

After conducting an extensive search on Google for examples related to my query, I was left empty-handed due to the generic name of the "connect-rest" package. My objective is to secure a server side API that I have built using the Node module "connect-re ...

What methods can be used to crack this number concealment system?

Hey there, I'm currently engaged in SMS marketing for my product and am extracting phone numbers from a website with the following link . This particular website obfuscates the contact numbers by assigning them class names like mobilesv icon-jie, wher ...

Adding a backslash in Angular: Tips and Tricks

I have a question about adding a backslash to a string that is returned from a div, for example Car1 \sold. Although I am able to retrieve the status, I am having trouble adding the backslash. Here is what I have tried so far: <span>{{addBackl ...

Using forEach in React to simultaneously set multiple properties and return destructured output within the setState function

The following is the initial code snippet: setRows((rows) => rows.map((row) => selected && row.node === selected.id ? { ...row, row.a: "", row.b: "", row.c: "" } ...

If a website undergoes changes to its user interface, can the selenium web automation still function effectively?

I have developed an automation script using Selenium in Java. I am curious to know if the code can still function properly even if there are changes made to the website's user interface. If the script is rendered ineffective after updates, is there a ...

Can you share the outcomes of executing a Node.js program in real-time?

Is there a method to execute a program (such as tcpdump) and have nodejs capture the console output in real-time to display in an HTML format without saving it? I am interested in running a program that displays information in the console, with the capabi ...

Fetching JSON data using Promise.all results in an empty response

I'm facing an issue in my code where I am trying to fetch data from two different JSON files and then return them as arrays. Even after implementing the solution below, it doesn't seem to be working as expected. Can someone guide me on how I can ...

Using Python with Selenium to choose an option from a dropdown selection

I'm struggling to choose an item from a dropdown menu. Take, for instance: <div class="col-sm-4 col-lg-2"> <label for="rangeFilter" class="sr-only">Date Range</label> <select class="selectpicker" id="rangeFilter" data-none ...

Using Regular Expressions in JavaScript to verify if an element from an array is contained within a string

Looking for a simple JavaScript code for a Vue application that will split the string into an array and check if any value is present in a different string. Here's what I have: let AffiliationString = " This person goes to Stony Brook" ...

Using script tags incorrectly (JavaScript platform game)

Currently, I am working on the 'create a platform game' project as outlined in Eloquent JavaScript, and I have encountered an issue related to script tags. As per the instructions in the book, we are advised to showcase our level using: <lin ...

Tips on sending a string as an argument in an onclick function

I am currently attempting to automatically add an anchor, and here is what I have tried: " <a id='" + x.NomFic + "' onclick='TransfererFica( " +x.Idtran +" , "+ x.NumVdr + " , '" + x.NomFic ...

Click on the text within a paragraph element

Is there a way to retrieve the selected text or its position within a paragraph (<p>)? I'm displaying a text sentence by sentence using a Vue.js loop of paragraphs. <p class="mreadonly text-left mark-context" v-for="line in ...

Customizing the language parameter for the apply button script on LinkedIn

Our company's website features the AWLI button which allows users to apply for jobs using their LinkedIn profile. <div name="widget-holder"> <script type="text/javascript" src="https://www.linkedin.com/mj ...

When you press the submit button, the screen automatically scrolls down but no action is taken

I'm currently utilizing Selenium WebDriver (Java) with the Firefox driver. Upon trying to click the 'Submit' button on a particular page, it only results in scrolling down the screen slightly. The button itself does not register the click, c ...

Is there still a need to preload dynamic images in the background?

Imagine you have HTML code that includes an image with a placeholder: <img class="lazy-load" src="http://via.placeholder.com/150/?text=placeholder" data-src="http://via.placeholder.com/150/?text=real%20image"/> At some stage, you want to implem ...

The default export of Nuxt, referred to as 'mod', could not be located

Using Nuxt with Typescript, I have created a custom component as shown below: <template> <div class="field"> <label class="label" v-if="typeof label !== 'undefined'">{{ label }}</label> <div class=" ...

Froala Editor: Innovative external toolbar that pops up when the button is clicked

In our project, we are implementing the latest version of Froala and aim to configure it so that the toolbar is activated by a separate external button, similar to Gmail where the editor initially does not display a toolbar. I attempted to modify the &apo ...

Ways to resolve the following C# problem: No match found for the specified testcase filter `FullyQualifiedName =`

As someone who is new to C# and Selenium, I have created several scripts successfully. However, I am encountering an issue when I try to create multiple methods or classes. Each time I stick to just one method or class, everything runs smoothly. I have sc ...

Utilizing Jquery for event handling in dynamically created table rows in a datatable

I am attempting to incorporate a function call "onblur" where I can input a new value in the TD cell. What I am looking to achieve is for the new value to be passed by the function to another JQuery script. Unfortunately, the datatable does not seem to rec ...

Retrieve particular key from document in MongoDB based on provided value

My Document retrieval process looks like this: async findOne(id: string) { return await this.gameModel.findById(id); } async update(id: string, updateGameDto: UpdateGameDto) { const game = await this.findOne(id) // This code snippet prints al ...