Home > Mobile >  Access child elements in Selenium
Access child elements in Selenium

Time:03-17

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  onclick="window.location.href='/user/36405612/3';">
    <div >
        <div  onclick="window.location.href='/user/36405612/3';">
            <img onclick="" src="blabla../user/170x170/male.jpg"  data-show-count="0" data-toggle="tooltip" title="" data-original-title="">

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

CodePudding user response:

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

CodePudding user response:

I'd recommend looking into Page Object model for automation. What it boils down to is that you have to tag each interactable element manually with a unique end-to-end tag e.g. <Button data_e2e='account__editEmail_button_sendCode'>, my logic is page__context_tagType_name.

Then i'd do something akin to this in the account.page.js file (this is using cypress, but logic is similar).

// extends from Page to use super.find (There's gotta be something similar in selenium)
class UpdateEmail extends Page {
  get ButtonSendVerificationCode()  { return super.find('account__editEmail_button_sendCode');}

  clickButtonSendVerificationCode() {
    this.ButtonSendVerificationCode.click();
  }
}

Then use this logic in your spec files any time you need to use the page file.

The page.js file:

module.exports = class Page {
  find(id) {
    return cy.get(`[data_e2e="${id}"]`);
  }

  open(path) {
    cy.visit(`${path}`);
  }
}
  • Related