-1
connections=driver.find_elements_by_css_selector("a span[class='mn-connection-card__name t-16 t-black t-bold']")
        print(len(connections))
for connection in connections:
    if connection.text == "XXX":
        connection.click()
        break

I am getting the following error in the if statement:

stale element reference: element is not attached to the page document

Mr. Discuss
  • 355
  • 1
  • 4
  • 13
  • Do you understand what causes a stale element? Do some reading on what causes it and then once you understand it, you will understand what you need to fix in your code. This question has been asked and answered many, many times here and elsewhere on the internet. – JeffC Aug 19 '20 at 14:56
  • Also, your CSS selector is not following the general style of a CSS selector. It looks more like an XPath and you may have issues if you don't correct it. A better CSS selector would be, `"a span.mn-connection-card__name.t-16.t-black.t-bold"`. – JeffC Aug 19 '20 at 14:58

1 Answers1

1

Stale element exception happen when properties of element on which your script is trying to perform some operation is changed. If you want to click a span with text "XXX" you can directly click on that:

WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//a[span[text()='XXX']]")))

If your requirement is to loop trough all such elements then:

connections=driver.find_elements_by_css_selector("a span[class='mn-connection-card__name t-16 t-black t-bold']")
        print(len(connections))
for i in range(len(connections)):

    connections=driver.find_elements_by_css_selector("a span[class='mn-connection-card__name t-16 t-black t-bold']") #Created Fresh element list, so it wont be stale 
     if connections[i].text == "XXX"
         connections[i].click
         break
rahul rai
  • 2,260
  • 1
  • 7
  • 17
  • thanks rahul. STALE issue is resolved.but the if statement leads to one more error "list index out of range" – sarmistha nayak Aug 20 '20 at 08:25
  • At which line you are getting Index out of range ? Also is your page changing since you get length of list and try to loop through it ? – rahul rai Aug 20 '20 at 08:43
  • in the line --if connections[i].text == "XXX"..there is a auto suggest search field..when i am entering a letter its displaying the list of name matched with it.If the name matched it supposed to click on it. – sarmistha nayak Aug 20 '20 at 09:03
  • If you want to click based on search for text inputted in your filed , please see this answer : https://stackoverflow.com/questions/63467976/how-can-i-select-a-search-suggestion-using-selenium-the-site-prevents-me-from-j/63469553#63469553 – rahul rai Aug 20 '20 at 09:12