Home > Software design >  Puppetteer Selects using Xpath
Puppetteer Selects using Xpath

Time:11-27

I am trying to select an option dynamically using puppeteer but I'm running into some problems on how to get it correctly. I need to get the actual value associated with the option tag. This is making my problem a bit harder. I searched a little bit and found that some people are using Xpath to make the problem a little easier to get, but it seems that my Xpath is not working correctly, as I'm getting an error ->

The string '//select[@id = "wrestler"]/option[text() = Henri Mugnier]' is not a valid XPath expression.

Henri Mugnier is at index 0 in my holderArr array.

Here is my small code snippet.

const option = (await frame.$x(
    `//select[@id = "wrestler"]/option[text() = ${holderArr[i].name}]`
))[0];

holderArr is getting passed in from another function, it's an array of objects. The dropdown is a list of names, but the value for each of them is just random numbers, So I'm hoping that using an xpath and then grabbing the value with a function like this

const value = await (await option.getProperty('value')).jsonValue();

Steps to reproduce:

  1. Go to https://www.trackwrestling.com/seasons/
  2. 2021-22 High School Boys > select 'Tennessee Secondary School Athletic Association'
  3. Click 'Team' at the top
  4. Select any team
  5. Select 'Matches' or More
  6. Select Matches (This dropdown is the one I'm trying to access)

CodePudding user response:

Your XPath,

//select[@id = "wrestler"]/option[text() = Henri Mugnier]

is syntactically invalid. Add quotes around Henri Mugnier:

//select[@id = "wrestler"]/option[text() = "Henri Mugnier"]

So, update your code to be:

//select[@id = "wrestler"]/option[text() = "${holderArr[i].name}"]`
                                           ^                    ^

That will take care of your immediate error. Whether the corrected XPath works will depend on your markup, which you've not shown.

CodePudding user response:

This is how I ended up getting it to work. This will give you the value property on the option tag using puppeteer.

 let [optElementHandle] = await frame.$x(`//select[@id="wrestler"]//option[contains(text() , "${holderArr[i].name}")]`)
    const text = await optElementHandle.getProperty('value')
    const value = await text.jsonValue()
  • Related