How to click a button class using selenium in Python

Viewed 460
<div class="wrapper">
 <button class="w-full h-14 pt-2 pb-1 px-3 bg-accent text-dark-1 rounded-full md:rounded select-none cursor-pointer md:hover:shadow-big focus:outline-none md:focus:bg-accent-2 md:focus:shadow-small ">
    <div class="font-medium">
      <div class="text-17 md:text-18 md:font-bold leading-18">Enter</div> 
        <div class="text-13 md:text-12 font-normal md:font-medium leading-normal">2 hours</div>
    </div>
 </button>
</div>

So I'm trying to click this button but it has a huge class name in CSS. One of the ways possible is to use 'driver.find_element_by_css_selector' but i'm not sure if I am doing it right? I'd prefer an approach where I don't have to use the 'css_selector'. But if that is the only way I guess that'll have to do.

I tried this, but it did not seem to work:

self.driver.find_element_by_css_selector('.w-full h-14 pt-2 pb-1 px-3 bg-accent text-dark-1 rounded-full md:rounded select-none cursor-pointer md:hover:shadow-big focus:outline-none md:focus:bg-accent-2 md:focus:shadow-small ')

Any suggestions? Thank you.

2 Answers

Try this

btn = self.driver.find_element_by_css_selector('.w-full h-14 pt-2 pb-1 px-3 bg-accent 
text-dark-1 rounded-full md:rounded select-none cursor-pointer md:hover:shadow-big 
focus:outline-none md:focus:bg-accent-2 md:focus:shadow-small ')

btn.click()

Use following locator to identify the element.

Css selector :

self.driver.find_element_by_css_selector("div.wrapper >button:nth-of-type(1)").click()

Xpath :

self.driver.find_element_by_xpath("//div[@class='wrapper']/button[1]").click()

Ideally you should use WebDriverWait() and wait for element clickable

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.wrapper >button:nth-of-type(1)"))).click()

You need to import below libraries.

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