Home > Software engineering >  PuppeteerSharp Get Selected Dropdown
PuppeteerSharp Get Selected Dropdown

Time:04-14

Hello and thanks for taking the time to read this.

I'm currently trying to scrape a bunch of product from BackMarket and am stuck on trying to get the "selected" value of a drop down IE :

<select id="id_wifi" name="wifi" >
       <option value=""></option>                                                              
       <option selected="" value="Oui">Oui</option>                                 
       <option value="Non">Non</option>  
</select>

In this case i'd like my string to store the "Oui" value. so i tried a bunch of method all of them unsuccessful like :

var content = await handle.EvaluateFunctionAsync<string>("option => option.value", handle);

but the first option is returning an empty string and the second option is returning null. I must admit i don't really know what i'm trying to do.

I'd appreciate it if someone could point me in the right direction

Thanks a lot.

EDIT :

In fact it's just my dumb mistake that made me lose a lot of time, this example is working fine. The product i was interacting with just had the "" value selected.

CodePudding user response:

From the examples in the docs, it looks like you have to do this:

// select the tag first
var element = await _page.QuerySelectorAsync("h1 > strong > a");

// then get the attribute
var url = await element.EvaluateFunctionAsync<string>("e => e.getAttribute('href')");
// OR
var url = await _page.EvaluateFunctionAsync<string>("e => e.getAttribute('href')", element);
// OR
var url = await (await element.GetPropertyAsync("href")).JsonValueAsync<string>();

// OR all in one
var url = await _page.EvaluateExpressionAsync<string>($"document.querySelector({"'h1 > strong > a'"}).getAttribute('href')");

You gotta apply this to the value of a select option, of course. Probably 'value' instead of 'href' and the correct selector.

  • Related