Python Selenium, select the next element in html DOM

Issue

i have to make some automation on a page.
The page consists of table where inside each td element i have 2 a tags, the first one with a class, the second one has no class or id.

i can easily select the one with the class, but how to get the other one? is there a way to select the element next to another one like in css?

this is a draft of the structure of the page

<table>
    <tr>    
        <td>
            <a class="mylink"> element 1 </a>
            <a>
                <img src="">
            </a>
        </td>
    </tr>
    <tr>    
        <td>
            <a class="mylink"> element 2 </a>
            <a>
                <img src="">
            </a>
        </td>
    </tr>
</table>

I can select the first one with

fileLinkClass = "mylink"
driver.find_element(by=By.CLASS_NAME, value=fileLinkClass)

but i need to select and click the a link without the class. How can i accomplish this?
Thank you so much

Solution

Try using css selector

For single element selection

 driver.find_element(By.CSS_SELECTOR,'.mylink + a')

For multiple elements selection

driver.find_elements(By.CSS_SELECTOR,'.mylink + a')

Make a list slicing then click. For example:

element = driver.find_elements(By.CSS_SELECTOR,'.mylink + a')
element = element[0].clik()
element = element[1].clik()

Answered By – F.Hoque

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published