Home > Blockchain >  How to get FIRST level children via Selenium
How to get FIRST level children via Selenium

Time:09-22

I have seen quite a few replies but for some reason NONE of them work and they always return all the children not just FIRST level

Here is one such answer: How to get first layer sub elements only in python selenium

They all suggest a CSS selector as in using nth-child(##)

Here is my data:

<**table**>
    <**tbody**>
        <**tr**>   // I want to only get this
            <**td**>td 1</td>
            <**tr**><td>Nested 1</td></**tr**>  // don't want this tr
            <**td**>td 2<**/td**>
            <**tr**><**/tr**>  // don't want this
            <**/tr**>
            <**tr**>   // I want to only get this
                <**td**>td 3<**/td**>
                <**tr**><**/tr**>  // don't want this
                <td>td 4</td>
                <tr></tr>  // don't want this
            </tr>
    <**/tbody**>
<**/table**>

CodePudding user response:

Best practice is to put an id field on each element, so that such problems become trivial. If you can, do that, so that your selector is just #my-id.

However, barring that you have to do some kind of awkward selector. nth-child would work as long as you are certain that the element you want is fixed. In this case table > tbody > tr:nth-child(1)

Barring that, you're out of luck in your exact case.

CodePudding user response:

Unfortunately , I do not own the HTML code and as such must live with it. I tried "table > tbody > tr:nth-child(1)" and it does not work. It gives me all descendants, rather than direct descendants :-(

  • Related