Oxymoronica
Oxymoronica

Reputation: 111

How to select this button using Python and Selenium?

I am trying to use Python and Selenium to click either Yes or No on these buttons:

enter image description here

The HTML for these buttons is as follows:

enter image description here

I've tried to select based on the XPath:

isbnButton = browser.find_elements_by_xpath("//a[@data-toggle='haveisbn'")

as suggested by a friend, but it's giving me an error that says the string is not a valid XPath expression. I know pretty much nothing about XPath and am doing a tutorial right now while I await answers, but I'm hoping someone can guide me in the right direction.

What I originally tried was:

dontHaveISBN = driver.find_elements_by_class_name('btn radio btn-radio btn-primary not-active w-100')
dontHaveISBN[1].click()

but that wasn't recognizing any elements.

How would you select and click on these buttons?

Upvotes: 0

Views: 92

Answers (3)

Guy
Guy

Reputation: 50899

In the xpath try you forgot the closing ], that's why it isn't valid. But there is a bigger issue with this locator: it matches the NO button as well.

In the class_name try you gave multiple classes as parameter, find_elements_by_class_name receives only one class as parameter.

data-id attribute seems to be unique, you can use it

# Yes button
driver.find_element_by_css_selector('[data-id="1"]')

# No button
driver.find_element_by_css_selector('[data-id="0"]')

# using xpath
driver.find_element_by_xpath('//a[@data-id="1"]')

Or using the text

driver.find_element_by_link_text('Yes')

driver.find_element_by_xpath('//a[text()="Yes"]')

Upvotes: 1

cruisepandey
cruisepandey

Reputation: 29362

You can try with this code :

wait = WebDriverWait(driver, 10)
yes_button = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'Yes')))
yes_button.click()  

It's better to use Link Text than XPATH.

In case you want to use only xpath then that would be :

//a[text()='Yes']

Note that you will have to import these :

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

If you want to learn more about xpath then you can refer this link

Hope this will help.

Upvotes: 1

brain_dead_cow
brain_dead_cow

Reputation: 83

You can give it a try with xpath again (try to copy exactly the xpath from the source code):

dontHaveISBN=driver.find_element_by_xpath('xpath_here')
dontHaveISBN.click()

Upvotes: 1

Related Questions