What is the best way to implement automation for this task using Selenium WebDriver?

As a newcomer to Selenium Webdriver (Js), I am eager to learn the basics but have hit a roadblock with a specific example:

My current challenge is automating a Google search for "Diablo 2 Resurrected days until release" and then displaying the remaining days in the console from the search results.

The issue I'm facing revolves around displaying the days left in my console. It seems like the element I'm trying to retrieve using .getText() isn't available when the webdriver attempts to locate it. I've tried using driver.sleep() and implicitlyWait without success. Both xpath and css selectors didn't work for me either. Here's the snippet of my code:

const {Builder, By, Key, until, WebDriver} = require("selenium-webdriver");
const { elementIsVisible } = require("selenium-webdriver/lib/until");
require("chromedriver");

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

driver.get("https://google.com");

// Handling cookie accept button
driver.findElement(By.css("#L2AGLb > div")).click();

driver.findElement(By.css('body > div.L3eUgb > div.o3j99.ikrT4e.om7nvf > form > div:nth-child(1) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input')).sendKeys('Diablo 2 Resurrected days until release');

driver.findElement(By.xpath('/html/body/div[1]/div[3]/form/div[1]/div[1]/div[3]/center/input[1]')).click();

driver.findElement(By.xpath('/html/body/div[7]/div/div[9]/div[1]/div/div[2]/div[2]/div/div/div[1]/div/div[1]/div[1]/div[1]/div/div[2]/div/div[1]')).getText().then(txt => {
    console.log("Do D2R relias: " + txt)
    }).catch(err => {
        console.log('error!', err);
});

Encountered Error Message:

error! NoSuchElementError: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[7]/div/div[9]/div[1]/div/div[2]/div[2]/div/div/div[1]/div/div[1]/div[1]/div[1]/div/div[2]/div/div[1]"}

Edit: Issue Solved! Below is the updated working code

const {Builder, By, Key, until, WebDriver} = require("selenium-webdriver");
require("chromedriver");
let driver = new Builder().forBrowser("chrome").build();

async function howManyDaysTillDiablo2ResurrectedRelease() {
    await driver.get("https://google.com");
    await driver.findElement(By.css("#L2AGLb > div")).click();
    await driver.findElement(By.css('body > div.L3eUgb > div.o3j99.ikrT4e.om7nvf > form > div:nth-child(1) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input')).sendKeys('Diablo 2 Resurrected days until release');
    await driver.findElement(By.xpath('/html/body/div[1]/div[3]/form/div[1]/div[1]/div[3]/center/input[1]')).click();

    let ele = await driver.wait(until.elementLocated(By.css("div[data-attrid*='calculate:how_many_days_away'][role='heading'] div")), 10000);
    let foo = await ele.getText();

    await driver.findElement(By.css("div[data-attrid*='calculate:how_many_days_away'][role='heading'] div")).getText().then(foo => {
        console.log("Do D2R relias: " + foo)
        }).catch(err => {
            console.log('error!', err);  
})};

howManyDaysTillDiablo2ResurrectedRelease();

Answer №1

It appears that the xpath you're currently using was obtained from developer tools and is an absolute xpath rather than a relative xpath.

Since you mentioned you're a beginner, I suggest taking the time to learn CSS selectors and xpaths so you can create your own.

Here's a CSS selector you can use:

div[data-attrid*='calculate:how_many_days_away'][role='heading'] div

You can implement it like this:

driver.findElement(By.css("div[data-attrid*='calculate:how_many_days_away'][role='heading'] div")).getText()

Update:

let element = await driver.wait(until.elementLocated(By.css("div[data-attrid*='calculate:how_many_days_away'][role='heading'] div")), 10000);
let text = await element.getText();

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

Tribal Code Typescript Compiler

Typescript is a great alternative to Javascript in my opinion, but it bothers me that it requires node.js as a dependency. Additionally, I find it frustrating that there seems to be only one compiler available for this language, and it's self-hosted. ...

Transfer an Array of Objects containing images to a POST API using Angular

Looking to send an array of objects (including images) to a POST API using Angular and Express on the backend. Here's the array of objects I have: [{uid: "", image: File, description: "store", price: "800"} {uid: "f ...

What is the best way to pass a div element and a variable from a Child component back to a Parent component in Next.js/React?

My goal is to create a webapp that, when an item in the list generated by the child component is clicked, displays the corresponding image in a div within the parent component. After some trial and error, I managed to generate the list in the child compone ...

Create a loop to iterate through dates within a specified range using the Fetch API

When I need to get the exchange rate from the bank for a specific interval specified in the input, I follow these steps. The interval is defined as [startdate; enddate]. However, in order to make a successful request to the bank, the selected dates must be ...

Managing the Firefox print dialog box using Selenium

Check out my code snippet below: from selenium.webdriver import Firefox from selenium.webdriver.common.keys import Keys url = 'https://finance.yahoo.com/' driver_path = 'geckodriver.exe' browser = Firefox(executable_path = driver_path) ...

Unraveling the mysteries of webpack configuration

import * as webpack from 'webpack'; ... transforms.webpackConfiguration = (config: webpack.Configuration) => { patchWebpackConfig(config, options); While reviewing code within an Angular project, I came across the snippet above. One part ...

Selenium IDE: The Perfect Tool for Seamlessly Logging into an Account

I'm currently working on testing the successful login functionality of an account using Selenium IDE. Does anyone know of a specific command in Selenium IDE that I can utilize to verify if I can log into my Facebook account, for example? Any assistan ...

Ensure the vertical dimension of the webpage is properly maintained

I am currently working with a client who has requested a website design with a specific height for the content section. The Inquiry: Is it possible to automatically create a new page for text that exceeds the maximum height of the content section on the ...

Exploring the world of HighCharts

I am trying to use Highcharts to calculate and visualize the magnitude of a complex number. Currently, my code is displaying the real and imaginary values separately on the graph. However, I seem to be facing issues with the "For loop" that I implemented ...

The process of registering with JWT tokens and the challenge that arises when a token expires

I had the idea to implement a registration process that requires users to provide their username, email (which must not already exist in the database), password, and confirm password. The project is built using NextJS with pages router and Typescript. impo ...

What is the best approach for updating data in a v-data-table dynamically?

I'm currently working on a node and electron application that utilizes vuetify to create a table (v-data-table) fetching data from an oracle database. The issue I'm facing is that even though the data changes based on the input value, the table f ...

When using jQuery to submit a form, the page is refreshed rather than actually submitting

I created a script to submit a form with a delay: $(document).ready(function () { $('#form-submit').on('click', function (event) { event.preventDefault(); // event.stopPropagation(); $('#big-dots-loade ...

Can a JavaScript (NodeJS) command or function be executed without halting the program in case of an error?

Is there a way in JavaScript to execute a function without interrupting the program if an error occurs? player.play('./sounds/throughQueue.mp3', function(err){ // let the program continue execution even if ther ...

Using a function to identify and check dynamically added checkboxes

I am using a PHP page that loads a group of categories from another PHP script as checkboxes. Here is the format for the checkboxes: <input type='checkbox' class='cat-selector' id='Business' data-toggle='checkbox&apo ...

Scrolling the y-axis with a fixed height limit to prevent overflow

My current dilemma is a seemingly simple one: <div class="container"> <div class="a"></div> <div class="b"></div> <div class="c"></div> </div>​ Within the container, there are 3 divs: A and B ...

Uncovering the inherent worth of an item pulled from a remote location using Vue.js

Currently, I am retrieving a list of countries by making an API call in VueX. The fetched data is then stored in a state using a mutation. Essentially, the countries are saved in a variable known as this.$state.getters.countryList, which can be accessed f ...

Tips for sending parameters to the function in the 'onclick' attribute in reactJS

My goal is to include an 'onclick' event for a checkbox in my code. Here's what I have attempted: <input type='checkbox' name="doneTask" value='done' onClick={removeTask(this)}/> The function 'remov ...

AJAX brings back the previous value from an array

I am currently working on a website that will showcase various artwork. The concept involves using JavaScript to run a php file when the page loads, which in turn queries the server for the names and IDs of the image files (artwork.jpg) and displays them a ...

Print the content from the selected tab in AngularJS UI tab

In my AngularJS application, I have implemented nested tabs and encountered an issue. I am trying to enable users to print the selected content list from both parent and child tabs. Is there a way to achieve this so that when a user clicks on "print list ...

utilizing numerous conditional renderings within a mapping function

Hello there, I'm curious if there is a more efficient method to display my todos. Currently, my code looks like this: { todos.map((todo) => ( todo.status === 1 && ( ...