Home > Enterprise >  how to extract selected value from dropdown box
how to extract selected value from dropdown box

Time:10-29

I have this piece of HTML

<div id="ctl00_cphMain_upAseguradora">
    <ul>
        <li>
            Régimen de Afiliación(*)
            <select name="ctl00$cphMain$ddlRegimenAfiliacion" id="ctl00_cphMain_ddlRegimenAfiliacion" disabled="disabled" class="aspNetDisabled comboBox">
                <option value="0">-Seleccione-</option>
                <option selected="selected" value="58">Contributivo</option>
                <option value="61">Especial</option>
                <option value="60">Pobre no afiliado</option>
                <option value="59">Subsidiado</option>
            </select>
        </li>
    </ul>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

for this part of a website

enter image description here

with selectorgadget i found the element that i need but im unsure on how to extract the selected option which in this case would be "Contributivo"

Regimen = detallepersona %>% html_elements("#ctl00_cphMain_upAseguradora ul:nth-child(1) li:nth-child(1) option") 

paste(Regimen)
[1] "<option value=\"0\">-Seleccione-</option>\n"           "<option selected value=\"58\">Contributivo</option>\n"
[3] "<option value=\"61\">Especial</option>\n"              "<option value=\"60\">Pobre no afiliado</option>\n"    
[5] "<option value=\"59\">Subsidiado</option>"             

Regimen %>%  html_attr("selected")
[1] NA         "selected" NA         NA         NA        

Regimen %>% html_text()
[1] "-Seleccione-"      "Contributivo"      "Especial"          "Pobre no afiliado" "Subsidiado"   

CodePudding user response:

Regimen = detallepersona %>% html_elements("#ctl00_cphMain_upAseguradora ul:nth-child(1) li:nth-child(1) option") 

Regimen1 = Regimen %>%  html_attr("selected")
Regimen1 = !is.na(Regimen1)
Regimen = Regimen %>% html_text()

Regimen[Regimen1]
[1] "Contributivo"

CodePudding user response:

Use an attribute or attribute = value css selector to target the child, of the parent select element which has id ctl00_cphMain_ddlRegimenAfiliacion, with the selected attribute. The space in the css selectors below is a descendant combinator.

#ctl00_cphMain_ddlRegimenAfiliacion [selected]

or

#ctl00_cphMain_ddlRegimenAfiliacion [selected=selected]

E.g.

Regimen = detallepersona %>% html_element('#ctl00_cphMain_ddlRegimenAfiliacion [selected]')%>%html_text()

Read more:

  1. https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
  2. https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator
  • Related