所以我对 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/