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

Access child elements in Selenium

Using Python’s Selenium I got the first div element because I needed the onclick element.

driver.find_element(By.CLASS_NAME, 'card-user-frontpage')
# I got the onclick element

This part is working for me. But now I also want to have the img element starting from the code above. I don’t want to use XPATH.

<div class="action-link card card-user-frontpage card-user-36405612 hover" onclick="window.location.href='/user/36405612/3';">
    <div class="card-block">
        <div class="userimage action-link pull-left placeholder" onclick="window.location.href='/user/36405612/3';">
            <img onclick="" src="blabla../user/170x170/male.jpg" class=" userimage-170x170 user-image" data-show-count="0" data-toggle="tooltip" title="" data-original-title="">

Like accessing the child elements in Selenium. Is that possible?

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

>Solution :

To locate the <img> element you can use either of the following Locator Strategies:

  • Using css_selector:

    element = driver.find_element(By.CSS_SELECTOR, ".card-user-frontpage > div.card-block > div.userimage.action-link.pull-left.placeholder > img")
    
  • With respect to the element you found:

    element = driver.find_element(By.CLASS_NAME, 'card-user-frontpage')
    # I got the onclick element
    my_element = element.find_element(By.CSS_SELECTOR, "div.card-block > div.userimage.action-link.pull-left.placeholder > img")
    
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