Last modified: Mar 24, 2023 By Alexander Williams
BeautifulSoup Get Option Value
Get the first option value using select_one
from bs4 import BeautifulSoup
# 👇 HTML code
html_doc = """
<select>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
"""
soup = BeautifulSoup(html_doc, 'html.parser') # 👉️ Create a BeautifulSoup object
option_tag = soup.select_one('option') # 👉️ Select the first option tag
value = option_tag['value'] # 👉️ Get the value of the option tag
print(value) # 👉️ Print the value
Output:
1
Get all options value using select
from bs4 import BeautifulSoup
# 👇 HTML code
html_doc = """
<select>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
"""
soup = BeautifulSoup(html_doc, 'html.parser') # 👉️ Create a BeautifulSoup object
option_tags = soup.select('select option') # 👉️ Select all the option tags
# 👇 Loop through all the option tags
for option_tag in option_tags:
value = option_tag['value'] # 👉️ Get option tag value
print(value) # 👉️ Print Value
Get the first option value using find
from bs4 import BeautifulSoup
# 👇 HTML code
html_doc = """
<select>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
"""
soup = BeautifulSoup(html_doc, 'html.parser') # 👉️ Create a BeautifulSoup object
option_tag = soup.find('option') # 👉️ Find the first option tag
value = option_tag['value'] # 👉️ Get the value of the option tag
print(value) # 👉️ Print the value
Output:
1
Get all options value using find_all
from bs4 import BeautifulSoup
# 👇 HTML code
html_doc = """
<select>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
"""
soup = BeautifulSoup(html_doc, 'html.parser')
option_tags = soup.find_all('option') # Find All Options Tag
for option_tag in option_tags:
value = option_tag['value']
print(value)
Output:
1
2
3