Omar Yacop
Omar Yacop

Reputation: 305

How to find an element with respect to its parent element with Selenium and Python

I am trying to scrape a website, but I need to search for an element whose parent is like this:

//div[@title="parent"]

People are talking about getting an element from its child. Is there a way to reverse it and find the child from its parent?

I want the /span with @title = "child" whose parent is //div[@title = "Search results."]

Upvotes: 2

Views: 2977

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193108

To locate the child element:

<span title="child"...>

within it's parent:

<div title="Search results."...>

you can use either of the following Locator Strategies:

  • Using css_selector:

    element = driver.find_element(By.CSS_SELECTOR, "div[title='Search results.'] span[title='child']")
    
  • Using xpath:

    element = driver.find_element(By.XPATH, "//div[@title='Search results.']//span[@title='child']")
    

Upvotes: 1

DonnyFlaw
DonnyFlaw

Reputation: 690

You can try to use

//div[parent::div[@title="parent"]]

or simply

//div[@title="parent"]/div

In Python code you can also use

parent = driver.find_element(By.XPATH, '//div[@title="parent"]')
child = parent.find_element(By.XPATH, './div')

Upvotes: 3

Related Questions