How to use a parent selector within a relative css selector in selenium python

Question:

I’m going to try my best to explain the problem.

This question is about selenium in Python. Consider this example:

for row in driver.find_elements(By.CSS_SELECTOR, "div[style='overflow: hidden;'] > div > div:nth-child(3)"):
    player = row.find_element(By.CSS_SELECTOR, '> div:first-child > span').text

Obviously, this second line is wrong, you can’t start a CSS query with >. However, that brings me to the question at hand, how exactly would I do something like this? How would I select all divs that are a direct child of the row element? I know you can use XPaths to achieve this, however, those are kind of a pain to work with (at least for me).

Asked By: okay

||

Answers:

To get all the child elements of the parent element with Selenium and CSS Selectors you can simply directly apply the find_element on specific web element (node) as following:

for row in driver.find_elements(By.CSS_SELECTOR, "div[style='overflow: hidden;'] > div > div:nth-child(3)"):
    player = row.find_element(By.CSS_SELECTOR, 'div:first-child > span').text

And in case you want to find the first direct child of the parent element :scope pseudo element can be used.
This will give you the first direct child of row node matching the div:first-child > span locator:

for row in driver.find_elements(By.CSS_SELECTOR, "div[style='overflow: hidden;'] > div > div:nth-child(3)"):
    player = row.find_element(By.CSS_SELECTOR, ':scope > div:first-child > span').text

See this answer for more explanations.

Answered By: Prophet