Avoid using sleep statements in Webdriverjs to prevent stale element reference issues

I've come across a block of code that utilizes action sequences to execute the following steps:

  • click on a link that directs to a specific page
  • wait for an input field to become visible on the page
  • click on the input field
  • clear any existing text in the field
  • type in a sequence of keys to specify a location
  • press the down arrow key (as the input uses autcomplete)
  • press the enter key to choose the correct location
  • click on the save button

I've heard that using driver.sleep() commands is not advised, but I can't seem to get the code to function correctly without them.

Below is the snippet of code:

driver.wait(until.elementLocated(By.css("a[href*='details/location']")), 5000)
driver.findElement(By.css("a[href*='details/location']")).click()
driver.wait(until.elementLocated(By.id("user_location")), 5000)
let loc = driver.findElement(By.id("user_location"))
let save = driver.findElement(By.xpath("//span[contains(text(), 'Save')]"))
driver.sleep(3000)
driver.actions().
    click(loc).
    sendKeys(Key.DELETE)
    .sendKeys('My location')
    .perform()
driver.sleep(1000)
driver.actions().
    sendKeys(Key.ARROW_DOWN).
    sendKeys(Key.ENTER).
    perform()
driver.sleep(1000)
driver.actions().
    click(save).
    perform()

Is there a more efficient approach to achieve this and could the stale element errors be avoided by eliminating the sleep statements? What causes these errors to occur when the sleep statements are removed?

Answer №1

There may be an issue with the timing between scraping the loc and save elements and using them in your code. Try reordering the code as shown below to see if that resolves the issue.

Additionally, you can optimize your code by combining lines 1 & 2 and lines 3 & 4 so that you only need to scrape the elements once using driver.wait().

driver.wait(until.elementLocated(By.css("a[href*='details/location']")), 5000).click()
let loc = driver.wait(until.elementLocated(By.id("user_location")), 5000)
# driver.sleep(3000) # you shouldn't need this sleep?
driver.actions()
    .click(loc)
    .sendKeys(Key.DELETE)
    .sendKeys('My location')
    .perform()
driver.sleep(1000)
driver.actions()
    .sendKeys(Key.ARROW_DOWN)
    .sendKeys(Key.ENTER)
    .perform()
driver.sleep(1000)
let save = driver.findElement(By.xpath("//span[contains(text(), 'Save')]"))
driver.actions()
    .click(save)
    .perform()

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

Navigating through pages using Jquery's show and hide functionality

How come my item is not returning? I used the .show() method on the item. <div id="back">< back</div> <div class="item">item</div> <div class="content">My content</div> $(function(){ $('.item').on(&apo ...

The functionality of cloning in jQuery may encounter an issue where the text field remains enabled if the user selects an option labeled "other

Currently, I am working on a jQuery clone with my existing code and everything is functioning well. In the first scenario, if the user selects other from the dropdown menu, the text field becomes enabled. In the second scenario, when the user clicks ...

Looping through links using Selenium in Python

I am working with an array of links and trying to access each one, print something from it, return to the main page, access the second link, and repeat this process until I have gone through all the links in the array. The issue I am facing is that only t ...

Add an asterisk before each line of comment when working in a TypeScript file using the VS Code IDE

Within my VS Code workspace, I am using the Typescript language and would like to format my comments across multiple lines with a specific style (look out for the star character) /** *@desc any text * any text */ However, when I attempt to write a comm ...

How come using a query object as a parameter for .limit() returns an empty array?

I am currently working on a mongoose query setup where I have a custom queryObject containing key-value pairs for specific records. If a key-value pair does not exist in the req.query, it is omitted from the queryObject. Oddly enough, when setting the que ...

Issue with compatibility between Capybara, Selenium, and ChromeDriver versions causing

Previously, I was able to successfully write system tests using Capybara for an old Rails project. However, when attempting to update the project following instructions from this solution and Chrome version 114.0.5735.90-1, a new version of Chrome had been ...

Using Firebase Authentication in Next.js with Server-Side Components

As I explore how to implement authentication using Firebase in my Next.js app, one thing that stands out is the need to initialize Firebase with our configuration details (apiKey, etc.). The concern I have is when using any Firebase function from a client ...

Utilizing window.location.pathname in Next.js for precise targeting

Are you familiar with targeting window.location.pathname in NEXT.JS? I encountered a red error while using this code in Next.js const path = window.location.pathname console.log(path) // I am able to retrieve the pathname here Then { ...

Selenium refuses to click on the element within a loop

Although the code works on its own, it fails to work when incorporated into a loop. driver.get("https://www.esky.pl/okazje/16578/WMI-EDI-FR") i = 1 departure_date_clickable = False while not departure_date_clickable: try: time.sleep(5) ...

Disable the javascript link on small devices

I currently have a javascript link (Trustwave) on my desktop website theme that I need to deactivate when viewed on mobile devices: Located in footer.tpl: <div style="position:absolute; margin-left:100px; margin-top:50px"> <script type="text/j ...

Converting hexadecimal to binary using Javascript or Typescript before writing a file on an Android or iOS device

Hey everyone! I'm facing a puzzling issue and I can't seem to figure out why it's happening. I need to download a file that is stored in hex format, so I have to first read it as hex, convert it to binary, and then write it onto an Android/ ...

Distinguishing Between Model and View State Management in AngularJS

As I work on a complex single page application in Angular, I find myself needing to manage two types of data. First, there is the Model data which pertains to information retrieved from and sent to the backend API server. Second, there is ViewState data wh ...

What is the process of integrating ES6 modules with app.get in a Node/Express routing application?

After researching the benefits of ES6 export, I made the decision to implement it in a NodeJS/Express project instead of using module exports. The MDN documentation explained that export is used as shown below: export function draw(ctx, length, x, y, color ...

Guide to activating a function by tapping anywhere on a webpage in iPhone Safari

I am attempting to implement a jQuery function that will change the text of a div in the iPhone browser when any area of the page is clicked. Here is my current setup: <div id="alternative_text">traduit</div> <script type="text/javascript ...

Tips for effectively showcasing JSON in an Angular directive

I am facing an issue with my Angular app that utilizes ui-router. I have set up a service and directive, but I am unable to display JSON data. Surprisingly, it works perfectly fine without the directive when I directly display it in the main template (home ...

A creative way to display a div upon hovering over a link dynamically

My website has dynamically generated a tags, each with its own corresponding div containing unique content and height. I want to make it so that when a user hovers over an a tag, the matching div is displayed. The div should appear at the position of the m ...

Executing Knex promises sequentially within a for loop

I have recently started to dive into Node and asynchronous coding, but I am struggling with a fundamental concept. I am trying to seed a database using knex, reading data from a CSV file and iterating through the rows in a for loop. In each iteration, I ne ...

What would cause this to result in a blank array?

I have a main component that contains multiple sub-components, which I navigate between by clicking on different elements. These sub-components are all Vue files. What I am trying to achieve is to dynamically highlight the active component when it is bein ...

What is the method for configuring automatic text color in CKEditor?

https://i.sstatic.net/yEM3p.png Is there a way to change the default text color of CKEditor from #333333 to #000000? I have attempted to modify the contents.css in the plugin folder: body { /* Font */ font-family: sans-serif, Arial, Verdana, "Tr ...

What is the best way to pass my request data to my $scope variable?

I'm currently facing a challenge with this particular topic. My goal is to add the response data that I retrieve from Express to my angular $scope and then direct the user to their profile page. This is how my Controller Function is structured: $sc ...