Home > Mobile >  Python Selenium, select the next element in html DOM
Python Selenium, select the next element in html DOM

Time:06-01

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 > element 1 </a>
            <a>
                <img src="">
            </a>
        </td>
    </tr>
    <tr>    
        <td>
            <a > 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

CodePudding user response:

You can use xpath selector

'//td/a[2]'

to find all second 'a's under a 'td'

CodePudding user response:

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')

To click 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()
  • Related