skip to Main Content

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


  1. Chosen as BEST ANSWER

    well i figure it out my self with the following code:-

    dropdown =  soup.find('select')
    selected = dropdown.select_one('option[selected]')
    print(selected['value'])
    

  2. just set True for dropdown.find

    dropdown = soup.find('select')
    
    selected_option = dropdown.find('option', selected=True)
    if selected_option:
    print(selected_option['value'])
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search