Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Selenium in Python to click/select a radio button

Tags:

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?

like image 746
Das Bruno Avatar asked Jan 24 '14 00:01

Das Bruno


People also ask

How do you select radio button in Selenium?

Also, we can select Radio buttons by using the click() method. Selenium also offers validation methods like isSelected(), isEnabled() and isDisplayed(). We can use these methods before performing any operation to make sure radio buttons are in the correct state.

How do you select a button in Selenium Python?

We can click a button with Selenium webdriver in Python using the click method. First, we have to identify the button to be clicked with the help of any locators like id, name, class, xpath, tagname or css. Then we have to apply the click method on it. A button in html code is represented by button tagname.

How does xpath select radio button in Selenium?

xpath("//input [@name='group1']")). size(); The above line of code calculates the number of radio buttons whose name is group1. Now, we will handle the radio buttons by using the index of a particular radio button.


1 Answers

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

browser.find_element_by_css_selector("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)

  • In Python binding, find_elements_by_css doesn't exist, it's called find_elements_by_css_selector. One should be able to look at the exception message and look back into documentation here and figure out why.
  • Notice the difference between find_element_by_css_selector and find_elements_by_css_selector? The first one finds the first matching element, the second one finds a list, so you need to use [0] to index. Here is the API documentation. The reason why I use the latter, is because I copied your code, which I shouldn't.
like image 71
Yi Zeng Avatar answered Sep 20 '22 16:09

Yi Zeng