Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

java - Selenium issue : stale element reference: element is not attached to the page document - After clicking on expected text

I have an issue with a selenium web test I'm executing. I keep getting a stale element reference error after clicking and taking me to the next page(which is correct)


WebDriver driver = DriverFactory.getWebDriver()

WebElement PositionTable = driver.findElement(By.xpath('//td[2]/table/tbody/tr/td/table'))

List<WebElement> Rows = PositionTable.findElements(By.tagName('tr'))

println('No. of rows: ' + Rows.size())


table: for (int i = 0; i < Rows.size(); i++) {
    
    List<WebElement> Cols = Rows.get(i).findElements(By.tagName('td'))
    
   for (int j = 0; j < Cols.size(); j++) {
       if (Cols.get(j).getText().equalsIgnoreCase(ExpectedPosition)) {
           
           
          Cols.get(j).findElement(By.tagName('a')).click()
          WebUI.delay(5)

          table: break
          
          } 
          }
            
          }
question from:https://stackoverflow.com/questions/65938153/selenium-issue-stale-element-reference-element-is-not-attached-to-the-page-do

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If clicking a button changes anything in the page html , the reference gets lost. You have find all elements again. So change your code as below

WebElement PositionTable = driver.findElement(By.xpath('//td[2]/table/tbody/tr/td/table'))

List<WebElement> Rows = PositionTable.findElements(By.tagName('tr'))

println('No. of rows: ' + Rows.size())

Int countrow = 0 


table:     while(countrow<Rows.size) {
++countrow
PositionTable = driver.findElement(By.xpath('//td[2]/table/tbody/tr/td/table'))

Rows = PositionTable.findElements(By.tagName('tr'))
    
    List<WebElement> Cols = Rows.get(i).findElements(By.tagName('td'))
    Int countcol = 0 
    
   whil(countcol < Cols.size()) {
       ++countcol
       Cols = Rows.get(i).findElements(By.tagName('td'))
       if (Cols.get(j).getText().equalsIgnoreCase(ExpectedPosition)) {
           
           
          Cols.get(j).findElement(By.tagName('a')).click()
          WebUI.delay(5)

          table: break
          
          } 
          }
            
          }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...