1

So I'm pretty new in Python and I tried something for my own, using selenium and firefox. But I got a StaleElementRefereceException when I want to type into a text field in firefox with selenium using send_key()

I tried a lot of Solutions like How to avoid "StaleElementReferenceException" in Selenium? but doesn't help me much because mine is not a click(), it's a send_key.

    hshtg = "xyz"

    driver = self.driver
    driver.get(".......")
    #time.sleep(3)

    cmmnt_elem = driver.find_element_by_xpath('//textarea[@aria-label="Kommentar hinzufügen ..."]')
    cmmnt_elem.click()
    #time.sleep(3)

    cmmnt_elem.send_keys(hshtg)
    #time.sleep(3)
    cmmnt_elem.send_keys(Keys.RETURN)

But, I got those errors.

File ".....py", line 45, in comment_photo
cmmnt_elem.send_keys(hshtg)

......

selenium.common.exceptions.StaleElementReferenceException: Message: The element 
reference of <textarea class="Ypffh"> is stale; either the element is no longer 
attached to the DOM, it is not in the current frame context, or the document 
has been refreshed

tried this too: (cause of this: How to avoid "StaleElementReferenceException" in Selenium?)

attempts = 0
while attempts < 20:
try:
cmmnt_elem.send_keys(hshtg)
break
except Exception as e:
attempts+1

In case it's helpful, this is the field:comment field on instagram

Oleg Balan
  • 11
  • 3

1 Answers1

0

when you click the textarea the DOM will be modified, so it will give the error, there are two solution to fix it.

  • remove click() action

    cmmnt_elem = driver.find_element_by_xpath('//textarea[@aria-label="Kommentar hinzufügen ..."]')    
    cmmnt_elem.send_keys(hshtg)
    
  • Re-search the element after click

    cmmnt_elem = driver.find_element_by_xpath('//textarea[@aria-label="Kommentar hinzufügen ..."]')
    cmmnt_elem.click()
    
    cmmnt_elem = driver.find_element_by_xpath('//textarea[@aria-label="Kommentar hinzufügen ..."]')
    cmmnt_elem.send_keys(hshtg)
    
ewwink
  • 18,382
  • 2
  • 44
  • 54