简体   繁体   English

Selenium Python - 如何让我的程序在某个特定元素出现时单击它?

[英]Selenium Python - How do I make my program to click an particular element when it appeared?

I'm trying to make a bot that automatically opens my server for me.我正在尝试制作一个自动为我打开服务器的机器人。 The problem is there's a human verification check in that website.问题是该网站上有人工验证检查。 When the number of people in the queue is less than 300 a button appears.当队列中的人数少于 300 时,会出现一个按钮。 I want my bot to click that button when it appears but I dunno how to do it.我希望我的机器人在该按钮出现时单击它,但我不知道该怎么做。

Xpath of that button is //*[@id="confirm"]该按钮的 Xpath 是//*[@id="confirm"]

Let's say it takes 100 seconds for the queue to build up, you can wait till then with :假设队列建立需要 100 秒,您可以等到那时:

time.sleep(100)

You can also do it via Selenium with :你也可以通过 Selenium 使用:

browser = webdriver.Chrome()
browser.implicitly_wait(100)
    # 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

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

If you want to click on element then we have to wait till element able to receive click.如果你想点击元素,那么我们必须等到元素能够接收点击。 This way you are able to click whenever queue less than 300 in give timeout period 40 seconds (selenium by default use polling interval for wait condition every 500 milli second)通过这种方式,您可以在给定超时期限 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM