【问题标题】:StaleElementReferenceException when I try to click the "n others" in "Liked by someone and n others" of an Instagram post, using Selenium and Python当我尝试使用 Selenium 和 Python 在 Instagram 帖子的“某人和其他人喜欢”中单击“其他人”时,StaleElementReferenceException
【发布时间】:2019-12-12 13:59:33
【问题描述】:

如您所知,当您在桌面版 Instagram 上打开帖子时,它会显示“被某人和其他 400 人点赞”。我正在尝试使用硒单击“其他 400 人”按钮,这样我就可以继续抓取追随者的姓名。 我将按钮的 Xpath 检索为 /html/body/div1/section/main/div/div/article/div[2]/section[2]/div/div[2]/button

但是,出现了一个错误,即 StaleElementReferenceException。 以下是我的代码:

likes = driver.find_element_by_xpath("/html/body/div[1]/section/main/div/div/article/div[2]/section[2]/div/div[2]/button")
actions.move_to_element(likes).perform()
likes.click()

错误发生在第二行,actions.move_to_element(likes).perform()

我想知道是否有人知道我该如何解决它。

【问题讨论】:

    标签: python selenium instagram staleelementreferenceexception


    【解决方案1】:

    ElementNotInteractableException 在找到元素时发生,但您无法与之交互,因为例如元素被另一个元素隐藏或由于某种原因未显示并且不再可点击。此外,您没有说它在哪个步骤上因 StaleElementReferenceException 而失败。无论如何,在这种情况下,使用 Wait until an element is visible / clickable 可能会有所帮助。第一个解决方案可能是刷新页面并再次尝试相同的元素:

    driver.refresh()
    

    第二种解决方案是等待元素直到它可用:

    from selenium.webdriver.support import expected_conditions as EC
    
    likes = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[1]/section/main/div/div/article/div[2]/section[2]/div/div[2]/button")))
    
    likes.click()
    

    希望对你有帮助!

    【讨论】:

    • 我尝试了您的第二个解决方案,它奏效了!非常感谢!
    猜你喜欢
    • 2012-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    • 1970-01-01
    • 2012-09-17
    相关资源
    最近更新 更多