I've been trying to click the second button in the html code below without using
find_element_by_xpath
I want to try locating the element by class name but i keep getting error messages.
Html:
<div
<button type="button"
<span aria-hidden="true"></span>
<span >-</span>
</button>
<button type="button"
<span aria-hidden="true"></span>
<span > </span>
</button>
My code:
button = driver.find_elements(By.XPATH, "//button[contains(@class, 'btn-primary')]//*[(@class, 'mdi-plus')]/..").click()
Does anybody know how could I locate the button and click it without using xpath or full xpath?
CodePudding user response:
To click on the element with text as you can use either of the following Locator Strategy:
Using css_selector:
driver.find_element(By.CSS_SELECTOR, "button.btn.btn-primary.btn-fab > span.mdi-plus span.sr-only").click()
Using xpath:
driver.find_element(By.XPATH, "//button[@class='btn btn-primary btn-fab']//span[@class='sr-only' and text()=' ']").click()
Ideally to click on a clickable element you need 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, "button.btn.btn-primary.btn-fab > span.mdi-plus span.sr-only"))).click()
Using
XPATH
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn btn-primary btn-fab']//span[@class='sr-only' and text()=' ']"))).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
CodePudding user response:
Selenium already has a method for that called driver.find_element_by_class_name
So to find your object simply do button = driver.find_element_by_class_name("btn btn-primary btn-fab")
CodePudding user response:
You can simply use css selector to find the element that you want. Here there are two buttons under the div with class amount-control
. If you would like to find the first button under that div, you can use the find_element_by_css_selector
along with the following css selector:
button = driver.find_element_by_css_selector('div.amount-control > button:first-child')
If you would like to get the second button, just change the :first-child
to :nth-of-type(2)
like this:
button = driver.find_element_by_css_selector('div.amount-control > button:nth-of-type(2)')
CodePudding user response:
//button[@][.//span[@]]
Should also be a valid xpath that contains a span with that class to target the button.