Search code examples
rrselenium

Rselenium - click on search button gives error "element is not attached to the page document"


I want to enter a zip code and click on search for a website using Rselenium

library(RSelenium)  
library(netstat)
  
zip <- "601"

rs_driver_object <- rsDriver(browser = 'chrome',
                             chromever = "101.0.4951.41",
                             verbose = F,
                             port = free_port())

remDr <- rs_driver_object$client
remDr$open()
remDr$maxWindowSize()

# go to website
remDr$navigate("https://pizza.dominos.com/")
  
# locate the search box
address_element <- remDr$findElement(using = 'id', value = 'geo-search')

# locate the search button
button_element <- remDr$findElement(using = 'class', value = "btn-search")
  
# send the zip code
address_element$sendKeysToElement(list(zip))
  
# click on search
button_element$clickElement()
  

However, when I do the last step of clicking, it shows me the error:

  Selenium message:stale element reference: element is not attached to the page document
  (Session info: chrome=101.0.4951.67)

  Error:     Summary: StaleElementReference
  Detail: An element command failed because the referenced element is no longer attached to the DOM.
  class: org.openqa.selenium.StaleElementReferenceException
  Further Details: run errorDetails method

Solution

  • I was able to achieve this using the following code. The error stale element reference: element is not attached to the page document usually comes when the backend HTML data is changed and the xpath you used becomes outdated.

    # go to website
    remdr$navigate("https://pizza.dominos.com/")
    
    # locate the search box and enter the zip
    zip <- "601"
    address_element <- remdr$findElement(using = 'id', value = 'geo-search')$sendKeysToElement(list(zip))
    
    # click on search
    button_element <- remdr$findElement(using = 'xpath', value = "(//button[@class='btn-search'])[2]")$clickElement()