【问题标题】:Loop until button is available Python Selenium循环直到按钮可用 Python Selenium
【发布时间】:2021-01-12 12:45:37
【问题描述】:

我正在使用 python 和 webdriver 编写我的第一个“机器人”

我想循环播放,直到网站上出现特定按钮。我的想法是检查按钮是否可用。如果没有,请睡一分钟,重新加载,然后再次检查。但我不知道正确的语法,因为这个元素对我来说太复杂了。

有人有小费吗?

编辑:当产品售罄时,产品页面上不存在此按钮。我猜启用/禁用在这里不起作用,因为如果产品不可用,则该按钮不存在。我想我需要检查一下按钮是否存在。

【问题讨论】:

  • 您可以使用 try 和 catch 块。检查 webelement 的存在,如果发生异常,捕获它并继续循环。

标签: python selenium google-chrome webdriver bots


【解决方案1】:

你可以在 python selenium 中使用WebDriverWait 来等待元素被加载。或者您可以使用 javascript 检查该元素是否存在于 DOM 中:

    buttons = document.getElementsByClassName("mu-button mu-button--type_alternative add-to-cart");
    if (buttons.length == 0) {
        # it doesn't exist
    } else
    {
        # do something
    }

【讨论】:

    【解决方案2】:

    完整文档:https://selenium-python.readthedocs.io/waits.html

    element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, "myDynamicElement"))
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-12
      • 1970-01-01
      • 2012-11-27
      • 2020-12-29
      • 2021-08-12
      • 1970-01-01
      • 2022-06-11
      • 1970-01-01
      相关资源
      最近更新 更多