【问题标题】:Python-Selenium cannot perform the right click in the consecutive loopPython-Selenium 无法在连续循环中执行右键单击
【发布时间】:2017-06-01 08:26:41
【问题描述】:

我正在自动执行在我们的 Web 应用程序上创建文件夹结构的任务,它需要右键单击并打开上下文菜单,我可以从中添加新文件夹。

folder_path = "Folder A\Folder B\Folder C"
folder_path_list = folder_path.split('\\')
for folder in folder_path_list:
    try:
        folder = WebDriverWait(browser, 15).until(EC.element_to_be_clickable((By.CSS_SELECTOR,
                                "div.tree-row.selected + div.tree-children > div > div > a[title='{}']".format(folder))))
        folder.click()
        time.sleep(5)
    except:
        parent_folder = WebDriverWait(browser, 8).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.tree-row.selected > a > span.tree-label")))
        parent_folder.click()
        actionchains.context_click(parent_folder).perform()
        add_new_folder_icon = WebDriverWait(browser, 8).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "li.CMicon-add-location")))
        add_new_folder_icon.click()
        del parent_folder

此代码在循环中为每个文件夹运行,该循环在第一次迭代期间成功执行,但在第二次迭代中未能在第 3 行执行右键单击。它会引发 StaleElementReferenceException 错误。我尝试了以下解决方案,但没有成功

  • 添加了del 命令以在每个循环结束时清除parent_folder 变量。
  • 刷新整个浏览器页面并重新导航到我创建的最后一个文件夹,但它会引发相同的异常。

让我感到困惑的是,即使它能够找到元素并左键单击并选择它,它也仅执行右键单击会面临问题。

【问题讨论】:

  • 你可以尝试在 try except block 中使用它吗? while true: try: actionchains.context_click(parent_folder).perform() break except: print("failed")
  • 好的,我试过了,还是失败了。
  • @Chandral 你能在你的循环中添加完整的代码吗?
  • @ChandaKorat 我已经在循环中添加了代码 sn-p。谢谢。
  • 1.你可以在 click 和 context click 之间睡觉(1)吗? 2. 不同浏览器的情况是一样的吗? 3. 如果你的 try 块失败,它总是会执行相同的代码来处理相同的元素。无论循环中 folder_path_list 中的哪个文件夹。是有意的吗?

标签: python python-3.x selenium selenium-webdriver selenium-chromedriver


【解决方案1】:

动作链在哪里初始化?尝试在 except 循环中使用之前重新初始化动作链

actionchains = ActionChains(browser)
actionchains.context_click(parent_folder).perform()

【讨论】:

  • 谢谢,这行得通。为什么我必须在每个循环中初始化变量?
  • 当您调用 ActionChains 对象上的操作方法时,这些操作将存储在 ActionChains 对象的队列中。当您调用 perform() 时,事件会按照它们排队的顺序被触发。 StaleElementReferenceException 表示它正在尝试访问旧引用。
猜你喜欢
  • 2018-07-20
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-17
  • 2012-07-20
相关资源
最近更新 更多