1

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" class="form-control">
       <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.

Ekses
  • 13
  • 5
  • I don't understand what the problem is, specifically.. – jasie Apr 13 '22 at 14:12
  • @jasie well my first option is returning an empty string and my second attempt is returning null. I've looked at some JS puppeteer example to try and get me in the right direction and i think it's reproduced correctly but i'm unsuccessful at grabing the "selected" value. In this case i'm trying to grab the "OUI" in a string. thx for your help – Ekses Apr 13 '22 at 14:25
  • The docs examples look like this: https://gist.github.com/hlaueriksson/4a4199f0802681b06f0f508a2916164d#file-examples-cs (Search for GetPropertyAsync and EvaluateFunctionAsync on that page.) Does that help? – jasie Apr 13 '22 at 14:53
  • @jasie Thank you very much it did help, it made me realize that the code is not wrong... I was just focusing on a product that had the "" value selected in the first place. thx a lot for your assistance. – Ekses Apr 13 '22 at 15:03

1 Answers1

0

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.

jasie
  • 2,192
  • 10
  • 39
  • 54