Selenium Webdriver错误-旧元素引用

时间:2019-01-19 18:27:48

标签: python selenium

所以我尝试使用https://instagram.com

网站练习硒的技能

我可以使用硒查找对象并单击,无法向其发送密钥。

所以基本上,我尝试在Instagram上自动执行评论,找到了“添加评论”,成功单击了它,但是当我尝试发送密钥时出现错误。

代码段:

comment_picture = driver.find_elements_by_tag_name('textarea')
    for l in comment_picture:
        try:
            print l.get_attribute("class")
            l.click()
            time.sleep(1)
            l.send_keys('test')

错误部分:

消息:过时的元素参考:元素未附加到页面文档 enter image description here

预期结果应该是我可以对Instagram上的每张照片发表评论。 我不想要答案。我真的很想学习硒。如果有人知道我做错了,那么如果我得到提示而不是完整的答案,那就太好了。

3 个答案:

答案 0 :(得分:1)

stale element是因为单击时已修改元素,所以您必须像这样重新查找元素

comment_picture = driver.find_elements_by_tag_name('textarea')
index = 1 # xpath index start from 1
for txt in comment_picture:
    try:
        txt.click()
        time.sleep(1)
        # re-search the textarea
        txt = driver.find_element_by_xpath('(//textarea)[%s]' % index) 
        txt.send_keys('test')
        index = index + 1 

答案 1 :(得分:0)

.find_element_*函数返回的

元素引用来自初始页面加载。 click()时,您正离开初始页面,使所有元素引用都变得陈旧。在将密钥发送到新元素之前,您将需要再次调用find_elements。

答案 2 :(得分:0)

您必须确保您已登录并能够发表评论。 也executable_path='your/path'

from selenium import webdriver

from selenium.webdriver.common.keys import Keys
from time import sleep
driver = webdriver.Chrome(executable_path="/home/chromedriver")
driver.get('https://www.instagram.com/p/Bs0y4Myg3Hk/')
comment=driver.find_element_by_xpath('//*[@id="react-root"]/section/main/div/div/article/div[2]/section[3]/div/form/textarea')
comment.send_keys('hello')
comment.send_keys(Keys.RETURN)
sleep(10)
driver.close()