简体   繁体   中英

How do I make Selenium Python click on a button element?

So I just started using Selenium for Python and I am trying to click on a button element that is buried into a few div elements; I've tried so many things but nothing works. Everything in the code works besides the last part which is waiting for the button to be clickable and then clicking it. I would greatly appreciate some help here, thanks. :)

HTML:

html代码

Code trials:

我的蟒蛇代码

Error stacktrace:

我的python代码错误

css selectors will become your best friend,

you should always look to add as many attributes as possible

maybe_later_css = 'button[class="btn btn-danger"]'
# type str, '<tag-name>[<attribute-name> = <attribute-value>]'

driver.find_element_by_css_selector(maybe_later_css).click()

follow this format for all elements, its superior and works as expected every time

the only complication is when there exists multiple buttons with them same class name, in which case you should find a different attribute to fill the [] brackets

To click on **Maybe Later** button. Induce WebDriverWait () and element_to_be_clickable () and following XPATH or CSS Selector.

XPATH :

WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//div[@class='modal-footer']//button[@Class='btn btn-danger x' and text()='Maybe Later']"))).click()

CSS Selector:

WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"div.modal-footer button.btn.btn-danger.x[style='danger']"))).click()

You need to import following libraries.

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

The element with text as Maybe Later is within a Modal Dialog Box so to locate and click() on the element you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies :

  • Using CSS_SELECTOR :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.modal-footer#eFooter button.btn.btn-danger.x[style='danger']"))).click()
  • Using XPATH :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='modal-footer' and @id='eFooter']//button[@class='btn btn-danger x' and @style='danger']"))).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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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