Issue
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 class="bRadio" value="1" type="radio" id="main.Option1" name="main.Option" checked="checked">
<label class="col-form-label">Equal Width</label>
</li>
<li>
<input class="bRadio" value="2" type="radio" id="main.Option2" name="main.Option">
<label class="col-form-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")
Solution
from bs4 import BeautifulSoup
html = '''
<li>
<input class="bRadio" value="1" type="radio" id="main.Option1" name="main.Option" checked="checked">
<label class="col-form-label">Equal Width</label>
</li>
<li>
<input class="bRadio" value="2" type="radio" id="main.Option2" name="main.Option">
<label class="col-form-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'
Answered By - platipus_on_fire_333
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.