当我尝试使用 Selenium 和 Python 单击 Instagram post 的 "Liked by someone and n others" 中的 "n others" 时出现 StaleElementReferenceException

StaleElementReferenceException when I try to click the "n others" in "Liked by someone and n others" of an Instagram post, using Selenium and Python

如您所知,当您在桌面版 Instagram 上打开 post 时,它会显示 "Liked by someone and 400 others"。我正在尝试使用 selenium 单击“其他 400 个”按钮,这样我就可以继续抓取关注者的名字。 I retreived the Xpath of the button as /html/body/div1/section/main/div/div/article/div[2]/节[2]/div/div[2]/按钮

但是出现了一个错误,就是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()

不知道有没有人知道我该如何解决。

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()

希望对您有所帮助!