python selenium,无法单击循环中的按钮列表

发布于 2025-02-06 08:04:11 字数 385 浏览 1 评论 0原文

收集按钮元素作为列表的列表。但是,当我单击一个并使用execute_script()返回到以前时,我无法单击任何其他按钮。

btnContainer = self.driver.find_elements(By.XPATH,"//div[@class='mx-0']")
for item in btnContainer:
    item.click()
    time.sleep(3)
    self.driver.execute_script("window.history.go(-1)")

NB。该代码适用于列表中的第一个元素,然后断开。错误是“元素未连接到页面文档”。我尝试在新选项卡中打开按钮,但网站不支持在新选项卡中打开按钮。

有什么办法解决这个问题吗?

collect a list of button elements as a list. But when I click one and go back to previous using execute_script() I can not click any other button.

btnContainer = self.driver.find_elements(By.XPATH,"//div[@class='mx-0']")
for item in btnContainer:
    item.click()
    time.sleep(3)
    self.driver.execute_script("window.history.go(-1)")

NB. the code works for the first element in the list and then breaks. The error is "element is not attached to the page document" .I have tried opening the button in a new tab but the website does not support to open the button in a new tab.

Is there any way to solve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

决绝 2025-02-13 08:04:11

加载新站点时,则丢失了对先前的Webelements的引用,因此您必须再次找到元素。为此,只需通过索引i运行一个循环,在该索引> i 中,您可以找到所有按钮,然后选择i-the。

for i in range(999):
    btnContainer = self.driver.find_elements(By.XPATH,"//div[@class='mx-0']")
    if i < len(btnContainer):
        item = btnContainer[i]
        item.click()
        time.sleep(3)
        self.driver.execute_script("window.history.go(-1)")
        time.sleep(3)
    else:
        break

When a new site is loaded then the reference to the previous webelements is lost, so you have to find the elements again. To do this simply run a loop over an index i in which you find all the buttons and select the i-th one.

for i in range(999):
    btnContainer = self.driver.find_elements(By.XPATH,"//div[@class='mx-0']")
    if i < len(btnContainer):
        item = btnContainer[i]
        item.click()
        time.sleep(3)
        self.driver.execute_script("window.history.go(-1)")
        time.sleep(3)
    else:
        break
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文