I am trying to get a selected value from a html select tag in python. well, it is successful while option attribute is set to selected="selected" but website i am trying to scrap has different option attribute some thing like that:-
html = """
<select>
<option value="">Please select a vlalue</option>
<option selected value = "1">Male</option>
<option value = "2">Female</option>
</select>
"""
soup = BeautifulSoup(html, "html.parser")
dropdown = soup.find('select')
for options in dropdown.find_all('option', {'selected':"selected"}):
if options is not null:
print(options['value'])
so my above code can not get selected value: can any one figure it out?
2
Answers
well i figure it out my self with the following code:-
just set True for
dropdown.find
This code will correctly find the selected option and print its value. The key change is using selected=True in the find method, which matches any option with the selected attribute, regardless of its value.