没有这样的元素异常 selenium python

No such element exception selenium python

我正在尝试从消息中清除我的 Instagram 聊天。我为此编写了以下代码,但是当我尝试删除第二条消息时,threeDots 初始化行上出现了 NoSuchElementException,尽管 xpath 本身已正确编写。

if len(positionsArray) > 1:
      for i in range(len(chatMessagesArray)):

          # Click on three dots (else button)
          threeDotsXpath = browser.find_element_by_xpath(f"/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/div/div[{positionsArray[len(positionsArray) - 1] + 1}]/div[2]/div/div/div/button[1]").click()

          # Deleting message and confirmation of it
          deleteMessageDiv = browser.find_element_by_xpath(f"/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/div/div[{positionsArray[len(positionsArray) - 1] + 1}]/div[2]/div/div/div/div[2]/div/div[2]/div[4]/button").click()
          browser.find_element_by_xpath("/html/body/div[6]/div/div/div/div[2]/button[1]").click()

          positionsArray.remove(positionsArray[len(positionsArray) - 1])

Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/div/div[2]/div[2]/div/div/div/button[1]"}

我认为这是一个过时的元素错误。刷新您的应用程序(或浏览器)并重试。它可能会起作用。 示例代码: 请检查正确的语法。我只是在这里打字,以便了解如何写。

browser.refresh()
WebdriverWait(driver, 20).until(EC.presenceOfElementLocated(yourelement).click()

过时的元素错误很棘手。我建议您也查看此 link 以获得更多详细信息。

事实上,在 Instagram 布局的细节中。为了删除下一条消息,您需要将鼠标光标从负责打开聊天的 div 移开,我使用 ActionChains 做到了这一点。我只是先关注“常规”按钮(您可以使用聊天之外的任何元素来执行此操作),然后关注最后一条消息。

act = ActionChains(browser)
lastMessagesInChat = browser.find_elements_by_class_name("DMBLb")
# Focus on general folder button because of instagram chat specific
act.move_to_element(browser.find_element_by_xpath(generalPathButtonXpath)).perform()

# Focus on the last message div
act.move_to_element(lastMessagesInChat[len(lastMessagesInChat) - 1]).perform()

# Click on three dots(else button)
threeDotsXpath = browser.find_element_by_xpath(
f"/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/div/div[{positionsArray[len(positionsArray) - 1]}]/div[2]/div/div/div/button[1]").click()