Home > Net >  BeautifulSoup: Extract the label of checked radio button
BeautifulSoup: Extract the label of checked radio button

Time:07-22

I have the radio buttons followed. How can I get the text of the checked radio button by python3? In this example, it is Equal Width.

  <li>
      <input  value="1" type="radio" id="main.Option1" name="main.Option" checked="checked">
      <label >Equal Width</label>
  </li>
  <li>
      <input  value="2" type="radio" id="main.Option2" name="main.Option">
      <label >Variable Width</label>
  </li>

I can get the checked radio button by the followed. But I have no clue how to connect with the text (label) of the button.

temp = tags.find_all('input', {'class' : 'bRadio', 'type' : 'radio'})
soup = BeautifulSoup(str(temp), 'lxml')
checked = soup.find_all('input', checked="checked")

CodePudding user response:

from bs4 import BeautifulSoup

html = '''

  <li>
      <input  value="1" type="radio" id="main.Option1" name="main.Option" checked="checked">
      <label >Equal Width</label>
  </li>
  <li>
      <input  value="2" type="radio" id="main.Option2" name="main.Option">
      <label >Variable Width</label>
  </li>'''

soup = BeautifulSoup(html, 'html.parser')

def is_checked(tag):
    return tag.has_attr('checked')

wanted_text = soup.find(is_checked).find_next_sibling('label').text
print(wanted_text)

This returns:

'Equal Width'

CodePudding user response:

I think you should do this in JQuery:

<li>
        <input  value="1" type="radio" id="main.Option1" name="main.Option" onchange="getId(this.id)" checked>
        <label for="main.Option1" >Equal Width</label>
    </li>
    <li>
        <input  value="2" type="radio" id="main.Option2" name="main.Option" onchange="getId(this.id)">
        <label for="main.Option2" >Variable Width</label>
    </li>
    <p id="demo"></p>
    <script>
        function getId(params){
            let text = $("[for='"   params   "'").text();
            $(demo).text(text);
            // you can use wherever you want
        }
        // Setting a default value
        $(demo).text("Equal Width");
    </script>
  • Related