Reputation: 111
I am trying to use Python and Selenium to click either Yes or No on these buttons:
The HTML for these buttons is as follows:
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
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
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
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