Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access HTML elements in a nested fashion with Selenium and Python

I’m trying to figure out how to access HTML elements in a nested fashion through Selenium and Python.

For example I have: box = driver.find_element_by_tag_name('tbody') which represents the body of the data I’d like to mine. I’d like to iterate through each row in this body (each row characterized by a <tr> tag) using something like:

for driver.find_element_by_tag_name('tr') in box:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But obviously that’s not possible because box is a Selenium object and is non-iterable.

What’s the best way to do something like this?

>Solution :

An optimum approach would be to construct locator strategies which would traverse from the parent till the descendants as follows:

  • Using CSS_SELECTOR:

    for element in driver.find_elements(By.CSS_SELECTOR, "tbody tr"):
        print(element.text)
    
  • Using XPATH:

    for element in driver.find_elements(By.XPATH, "//tbody//tr"):
        print(element.text)
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading