简体   繁体   中英

How to click on a button using Selenium

I'm making some test with selenium on this page: https://www.justwatch.com/es/proveedor/hbo-max/peliculas

The first time you get in the page you must accept the privacy settings but i cannot get it to work. I've tried all the methods i now but it seems like i cant find the button i want so the program stops as the waiting time ends. The button i whant to click is:

<button role="button" data-testid="uc-save-button" class="sc-gsDKAQ eaUldE" style="margin: 0px 6px;">Guardar configuración</button>

I tried to locate the button by text, class and using the XPath but doesnt work.

WebDriverWait(driver, 5)\
.until(EC.element_to_be_clickable((By.CLASS_NAME, 'sc-gsDKAQ eaUldE'.replace(' ', '.'))))\
.click()

WebDriverWait(driver, 5)\
.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[2]//div/div/div/div/div[2]/div/div[2]/div/div/div/button[1]')))\
.click()

WebDriverWait(driver, 5)\
.until(EC.element_to_be_clickable((By.LINK_TEXT, 'Guardar configuración')))\
.click()

I will aprecciate your help.

To click on the desired element you can use either of the following locator strategies :

  • Using CSS_SELECTOR :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-testid='uc-save-button']"))).click()
  • Using XPATH :

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@data-testid='uc-save-button' and text()='Guardar configuración']"))).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