Wei-Xuan
Wei-Xuan

Reputation: 3

Python: How I get the html radio box checked?

I'm not familiar with Python and

I want to search if the radio box is checked.

here is my HTML code.

<input type="radio" name="radio1" value="1" checked>
<input type="radio" name="radio2" value="2"> 
<input type="radio" name="radio3" value="3" checked>

I try this code but it doesn't work

import requests
from requests.auth import HTTPBasicAuth

from bs4 import BeautifulSoup

res = requests.get('url', auth=HTTPBasicAuth('User', 'Password'))

soup = BeautifulSoup(res.text,'html.parser')
print soup.find(attrs={'name':'radio1'}).attrs['checked']
print soup.find(attrs={'name':'radio2'}).attrs['checked']
print soup.find(attrs={'name':'radio3'}).attrs['checked']

Upvotes: 0

Views: 2295

Answers (1)

Tiny.D
Tiny.D

Reputation: 6556

Try with has_attr:

from bs4 import BeautifulSoup

div_test = """
<input type="radio" name="radio1" value="1" checked/>
<input type="radio" name="radio2" value="2"/>
<input type="radio" name="radio3" value="3" checked/>
"""

soup = BeautifulSoup(div_test,'html.parser')
print soup.find('input',attrs={'name':'radio1'}).has_attr('checked')
print soup.find('input',attrs={'name':'radio2'}).has_attr('checked')
print soup.find('input',attrs={'name':'radio3'}).has_attr('checked')

Output:

True
False
True

Upvotes: 1

Related Questions