0

I'm trying to clear my Instagram chat from messages. I wrote the following code for this, but when I try to delete the second message, a NoSuchElementException on the threeDots initialization line appears, although the xpath itself is correctly written.

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]"}

2 Answers2

0

It's a stale element error I think. Refresh your app (or browser) and try again. It might work. Sample code: Please check the right syntax. I am just typing here so to have an idea of how to write.

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

Stale element error is tricky. I suggest you to check this link too for greater detail.

Anand Gautam
  • 2,018
  • 1
  • 3
  • 8
0

The fact is that in the specifics of the layout of Instagram. In order to delete the next message, you need to move the mouse cursor from the div responsible for the open chat, I did this using ActionChains. I just focus on the "General" button first (You can do this using any element outside the chat), and then focused on the last message.

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