python - 无法修复 StaleElementReferenceException @my send_keys

标签 python selenium browser

所以我对 Python 还很陌生,我使用 selenium 和 firefox 尝试了一些自己的东西。但是当我想使用 send_key() 使用 selenium 在 firefox 中的文本字段中输入内容时,出现 StaleElementRefereceException

我尝试了很多解决方案,例如 How to avoid "StaleElementReferenceException" in Selenium?但对我没有多大帮助,因为我的不是 click() ,这是一个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)

但是,我遇到了这些错误。

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

也尝试过这个:(原因:How to avoid "StaleElementReferenceException" in Selenium?)

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

如果有帮助,请输入以下字段:comment field on instagram

最佳答案

当您点击textarea时,DOM将被修改,因此会出现错误,有两种解决方案可以修复它。

  • 删除click()操作

    cmmnt_elem = driver.find_element_by_xpath('//textarea[@aria-label="Kommentar hinzufügen ..."]')    
    cmmnt_elem.send_keys(hshtg)
    
  • 点击后重新搜索元素

    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)
    

关于python - 无法修复 StaleElementReferenceException @my send_keys,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54012953/

相关文章:

python - 建议 "Author Identfication"的步骤?

python - MySQL升级后django未处理的异常

python - 如何修复 Python 中的 ARIMA 模型错误

python - IE 测试的 Selenium 问题

java - 当我在项目中添加新库时相关库的协调版本

python - numpy C API 中的 import_array 如何工作?

python - 如何通过css选择器选择标签

css - 编辑滚动条 (CSS/JQuery)

css - 基于感知性别的条件

linux - 开始构建我自己的 mozilla 的资源