I’m trying to get the selected option from <select>
element in HTML using BeautifulSoup, but I have a problem that the source HTML doesn’t indicate selected elements in code. The source looks like that:
<select class="class_name" name="Type" style="max-width: 170px; min-width: 135px;">
<option value="Value1">Value 1</option>
<option value="Value2">Value 2</option>
<option value="Value3">Value 3</option>
<option value="Value4">Value 4</option>
</select>
Meanwhile this is how the element looks in browser:
So when I try soup.find('select', class_="class_name")
, i only get a list of options, but not selected one:
<select class="class_name" name="Type" style="max-width: 170px; min-width: 135px;"><option value="Value1">Value 1</option><option value="Value2">Value 2</option><option value="Value3">Value 3</option><option value="Value4">Value 4</option></select>
What can help me in this case?
user25240278 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
In case that there is no indicator like selected
there will be no chance to pick the right one.
In case that there is an indicator:
soup.select_one('select option[selected]').get('value')
Example
from bs4 import BeautifulSoup
html = '''
<select class="class_name" name="Type" style="max-width: 170px; min-width: 135px;">
<option value="Value1">Value 1</option>
<option value="Value2">Value 2</option>
<option value="Value3" selected>Value 3</option>
<option value="Value4">Value 4</option>
</select>
'''
soup = BeautifulSoup(html)
soup.select_one('select option[selected]').get('value')