John M.
John M.

Reputation: 2712

Selenium: Get children with a specific class

Given a child element e, is there a good (or pythonic) way to find all children with tag div and a class cls? I've tried e.find_element_by_xpath('div[starts-with(@class, "cls")]') but that doesn't seem to search within e. It seems to return the first match in the tree.

Upvotes: 3

Views: 2081

Answers (1)

Andersson
Andersson

Reputation: 52665

Try below

children = e.find_elements_by_xpath('./div[contains(@class, "cls")]')

Note that you need to start your XPath with ./ that means direct child of current node (e)

If elements are dynamically generated by JavaScript, try to wait for them to appear in DOM:

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.common.by import By

children = wait(e, 10).until(EC.presence_of_all_elements_located((By.XPATH, './div[contains(@class, "cls")]')))

Upvotes: 5

Related Questions