【问题标题】:Selenium Python - How do I make my program to click an particular element when it appeared?Selenium Python - 如何让我的程序在特定元素出现时单击它?
【发布时间】:2020-01-31 13:58:50
【问题描述】:

我正在尝试制作一个自动为我打开服务器的机器人。问题是该网站中有人工验证检查。当队列中的人数少于 300 时,会出现一个按钮。我希望我的机器人在该按钮出现时点击它,但我不知道该怎么做。

那个按钮的Xpath是//*[@id="confirm"]

【问题讨论】:

标签: python python-3.x selenium


【解决方案1】:

假设队列建立需要 100 秒,您可以等到那时:

time.sleep(100)

您也可以通过 Selenium 使用:

browser = webdriver.Chrome()
browser.implicitly_wait(100)

【讨论】:

  • 但是排队时间每次都会变化。所以不可能给它设置时间延迟。
【解决方案2】:
    # if not visible will raise a exception
    try:
        element = WebDriverWait(driver, 20).until(
        EC.visibility_of_element_located((By.ID, "elementID"))

        # click
        driver.find_element_by_id("elementID").click()
    except Exception:
        # do action if not visible

来源:https://selenium-python.readthedocs.io/waits.html

【讨论】:

    【解决方案3】:

    如果你想点击元素,那么我们必须等到元素能够接收点击。这样,您可以在给定超时期限 40 秒内的队列少于 300 时单击(默认情况下,硒每 500 毫秒使用轮询间隔等待条件)

    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    element = WebDriverWait(driver, 40).until(
    EC.element_to_be_clickable((By.XPATH, "//*[@id="confirm"]")))
    element.click()
    

    【讨论】:

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