【问题标题】:No such element exception selenium python没有这样的元素异常 selenium python
【发布时间】:2022-01-04 17:10:52
【问题描述】:

我正在尝试从消息中清除我的 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])

消息:没有这样的元素:无法找到元素: {"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]"}

【问题讨论】:

    标签: python selenium xpath


    【解决方案1】:

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

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

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

    【讨论】:

    • 或许有不使用browser.refresh()的解决方案?你不能为我的代码这样做
    【解决方案2】:

    事实上,在 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 2018-03-21
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多