EL323 EL323 - 3 months ago 29
Python Question

how to select a radio button in selenium python?

<ul>

<li>
<label class="checkbox">
<input checked="checked" id="fechapublicacion" name="fechapublicacion" onclick="javascript: filtrarListado(&#39;fechapublicacion&#39;, this);" type="radio" value="0" />
<span>Cualquier fecha</span>
</label>
<input id="fechapublicacionhidden" name="fechapublicacionhidden" type="hidden" value="0" />
</li>
<li>
<label class="checkbox">
<input id="fechapublicacion" name="fechapublicacion" onclick="javascript: filtrarListado(&#39;fechapublicacion&#39;, this);" type="radio" value="1" />
<span>&#218;ltimas 24 horas</span>
</label>
<input id="fechapublicacionhidden" name="fechapublicacionhidden" type="hidden" value="0" />
</li>
<li>
<label class="checkbox">
<input id="fechapublicacion" name="fechapublicacion" onclick="javascript: filtrarListado(&#39;fechapublicacion&#39;, this);" type="radio" value="7" />
<span>&#218;ltimos 7 d&#237;as</span>
</label>
<input id="fechapublicacionhidden" name="fechapublicacionhidden" type="hidden" value="0" />
</li>
<li>
<label class="checkbox">
<input id="fechapublicacion" name="fechapublicacion" onclick="javascript: filtrarListado(&#39;fechapublicacion&#39;, this);" type="radio" value="15" />
<span>&#218;ltimos 15 d&#237;as</span>
</label>
<input id="fechapublicacionhidden" name="fechapublicacionhidden" type="hidden" value="0" />
</li>
</ul>


I am trying to select the last radio button. Since all of them have same id, how can i select the last one.

Any help will be appreciated.

Answer

Actually find_elements returns list that's why you are in trouble, you should try using find_element instead as below :-

browser.find_element_by_id("fechapublicacion").click()

Or if you want to use find_elements, You should try using index in returned list as below :-

browser.find_elements_by_id("fechapublicacion")[0].click()

Edited :- As I'm seeing in provided HTML, I'd is not unique there and you want to select last element with the id then try using find_elements and select last element by passing last index as -1 :

browser.find_elements_by_id("fechapublicacion")[-1].click()

Or you can also use find_element to point this element using unique css_selector as below :-

browser.find_element_by_css_selector("input#fechapublicacion[value='15']").click()