2

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."]

Omar Yacop
  • 305
  • 1
  • 6

2 Answers2

3

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')
DonnyFlaw
  • 581
  • 3
  • 9
1

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']")
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352