Ellie The Good Dog
Ellie The Good Dog

Reputation: 127

Selenium Click A Button, Using Python

I have tried to figure this out for a while - no luck.

I want to click this button:

<button name="showMoreButton" data-test-id="show-more-button" aria-label="Show More" type="button" class="uitk-button uitk-button-medium uitk-button-has-text uitk-button-primary">Show More </button >

I have been trying things like this I have found all over the place, but none work:

element_to_click = driver.find_element(By.xpath("//button[@data-test-id='show-more-button']").click()
element_to_click = driver.find_element(By.cssSelector(".uitk-button uitk-button-medium uitk-button-has-text uitk-button-primary")).click()

I think the first failure occurred because Selenium appears to be unable to handle "data-test-id" - something that strikes me a curious weakness...

I can't understand why the second failure occurred.

Thanks so much for any help.

Ellie The Good Dog

Upvotes: 0

Views: 846

Answers (2)

cruisepandey
cruisepandey

Reputation: 29362

There are lot of ways to deal with that. Here is a reliable solution.

Use Explicit wait

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.NAME, 'showMoreButton')))
element.click()

You would need to import from the below line :

from selenium.webdriver.support import expected_conditions as EC

or if you want to use XPATH or CSS_SELECTOR then you could try something like given below :

CSS :

element_to_click = driver.find_element(By.CSS_SELECTOR, "button[name='showMoreButton'].uitk-button.uitk-button-medium.uitk-button-has-text.uitk-button-primary")
element_to_click.click()

XPATH :

element_to_click = driver.find_element_by_xpath("//button[contains(text(),'Show More')]")
element_to_click.click()

Upvotes: 1

Sonali Das
Sonali Das

Reputation: 1026

Please use the code as below. You are missing one parenthesis and writing wrongly .find_element method.

driver.find_element_by_xpath("//button[@data-test-id='show-more-button']").click()

You can also use as below

driver.find_element_by_css_selector(".uitk-button uitk-button-medium uitk-button-has-text uitk-button-primary").click()

Upvotes: 0

Related Questions