Using Selenium in Python to select / select radio button

I am trying to select from a list of three buttons, but cannot find a way to select them. Below is the HTML I'm 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 using the following code:

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

These outputs are: SRF, COM, MOT

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

+8
python selenium selenium-webdriver
source share
5 answers

Use the CSS or XPath selector to directly select the value attribute, then click it.

 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 the OP must learn to look in the documentation)

  • find_elements_by_css does not exist in Python find_elements_by_css ; it is called find_elements_by_css_selector . You need to be able to watch the exception message and look back at the documentation here and find out why.
  • Notice the difference between find_element_by_css_selector and find_elements_by_css_selector ? The first finds the first matching element, the second finds the list, so you need to use [0] for indexing. Here is the API documentation. The reason I use the latter is because I copied your code, which should not.
+28
source share

In a for loop, you can use the click method.

 for i in browser.find_elements_by_xpath("//*[@type='radio']"): i.click() 
0
source share
 browser.find_elements_by_xpath(".//input[@type='radio' and @value='SRF']")[0].click 

In the end, it was a fix. I was getting errors without [0] that there is no click () attribute in the list (although there was only 1 match). Thanks for the help of user1177636!

0
source share

find_elements_by_css_selector worked for me,

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

Enter image description here

Selenium web switch

When I used xpath:

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

no switch selected

But I used css_selector:

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

radio switch selected

0
source share

All Articles