简体   繁体   English

如何使用 Selenium 单击按钮

[英]How to click on button using Selenium

I'm trying to click a button on a website with Selenium in python, and the button clicking works fine, I can see the button being clicked but the code stops running at that point and when I check the website in my normal browser I can tell that the button hasn't been clicked.我正在尝试在 python 中单击带有 Selenium 的网站上的一个按钮,并且该按钮单击工作正常,我可以看到该按钮被单击,但代码此时停止运行,当我在我的普通浏览器中检查该网站时,我可以告诉按钮没有被点击。 More specifically, I'm trying to click a start button for an aternos.org server, and it clicks fine, but the actual starting of the server doesn't go through for some reason.更具体地说,我正在尝试单击aternos.org服务器的start按钮,并且单击正常,但由于某种原因,服务器的实际启动并没有通过 go。

My code for the start button clicking:我的开始按钮点击代码:

start = driver.find_element(By.ID, 'start')
status = driver.find_element(By.CLASS_NAME, 'statuslabel-label').text
print(status)
if status == 'Offline':
    start.click()
    print('Starting server!')

Ideally, to locate and click any clickable element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies :理想情况下,要定位并单击任何可点击元素,您需要为element_to_be_clickable()诱导WebDriverWait ,并且您可以使用以下任一定位器策略

  • Using ID :使用ID

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "start"))).click()
  • Using CSS_SELECTOR :使用CSS_SELECTOR

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#start"))).click()
  • Using XPATH :使用XPATH

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='start']"))).click()
  • Note : You have to add the following imports:注意:您必须添加以下导入:

     from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC

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

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