Using Selenium in Python to click/select a radio button


Using Selenium in Python to click/select a radio button



I am trying to select from a list of 3 buttons, but can't find a way to select them. Below is the HTML I am working with.


<input name="pollQuestion" type="radio" value="SRF">
<font face="arial,sans-serif" size="-1">ChoiceOne</font><br />
<input name="pollQuestion" type="radio" value="COM">
<font face="arial,sans-serif" size="-1">ChoiceTwo</font><br />
<input name="pollQuestion" type="radio" value="MOT">
<font face="arial,sans-serif" size="-1">ChoiceThree</font>



I can find it by using the following code:


for i in browser.find_elements_by_xpath("//*[@type='radio']"):
print i.get_attribute("value")



This outputs: SRF,COM,MOT



But I would like to select ChoiceOne. (To click it) How do I do this?




5 Answers
5



Use CSS Selector or XPath to select by value attribute directly, then click it.


value


browser.find_elements_by_css("input[type='radio'][value='SRF']").click
# browser.find_element_by_xpath(".//input[@type='radio' and @value='SRF']").click



Corrections (but OP should learn how to look up in documentation)


find_elements_by_css


find_elements_by_css_selector


find_element_by_css_selector


find_elements_by_css_selector





WebDriver has no attribute 'find_elements_by_css'. I would prefer to use CSS, as I am taking it from CSS, but found more success adding [0] to the 2nd entry.
– Das Bruno
Jan 24 '14 at 17:21





actually it's find_element_by_css_selector("input[type='radio'][value='SRF']").click()
– sspross
Mar 9 at 6:37


find_element_by_css_selector("input[type='radio'][value='SRF']").click()



In your for loop you can use the click method.


for i in browser.find_elements_by_xpath("//*[@type='radio']"):
i.click()


browser.find_elements_by_xpath(".//input[@type='radio' and @value='SRF']")[0].click



This ended up being the fix. I was getting errors without the [0] there, that a list does not have a click() attribute (even though there was only 1 match). Thanks for the help user1177636!



find_elements_by_css_selector worked for me,


find_elements_by_css_selector


browser.find_elements_by_css_selector("input[type='radio'][value='SRF']")[0].click()



Enter image description here



Selenium webdriver Radio button click



When i used xpath :


driver.find_element_by_xpath("//input[@id='id_gender2']").click()



radio button not selected



But I used css_selector :


driver.find_element_by_css_selector("input#id_gender1").click()



radio button selected






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

PHP contact form sending but not receiving emails