Reputation: 73
This is my first question so if I missed some information or did anything wrong I already apologize for that. I am using a ChromeDriver to scrape through the Internet. The used language is Python in combination with Selenium.
I have an element which is a span tag that I stored in a variable called elem. I could find the parent element of elem
articles.append(elem.find_parent("a")['href'])
which was stored in that array articles. Now I need to find the ancestor element which is the span tag with the class saying "price": lowest line represents elem and the second line is the element I am looking for.
However, trying the same like before:
elem.find_parent("span")['class']
doesn't work out for me and I get a Nonetype Error. I have tried multiple other methods but always got a NoneType Error.
Thank you in advance.
Upvotes: 3
Views: 6204
Reputation: 4212
Parent selects the parent of the current node.
Lets take as an example the reputation span
element from Stackoverflow user's profile:
To go one level up with XPATH:
//span[@class='grid--cell ']
You can go one level up with /..
//span[@class='grid--cell ']/..
Using XPATH parent
:
//span[@class='grid--cell ']/parent::div[@class='grid gs8 fs-headline1']
parent
selects the parent of the current node
Using XPATH ancestor
//span[@class='grid--cell ']/ancestor::div[@class='grid gs8 fs-headline1']
The difference is that ancestor
selects not only the parent, but also grandparents and so on of the current element.
There is no a good way currently to do the same with CSS.
To find child elements I usually use //
for all siblings or /
for a direct sibling.
Upvotes: 6
Reputation: 1540
from selenium import webdriver
driver = webdriver.Chrome(executable_path="
C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify child element
l= driver.find_element_by_xpath("//li[@class='heading']")
#identify parent from child element with (..) in xpath
t= l.find_element_by_xpath("..")
# get_attribute() method to obtain class of parent
print("Parent class attribute: " + t.get_attribute("class"))
driver.close()
Solution from https://www.tutorialspoint.com/how-to-find-parent-elements-by-python-webdriver
Upvotes: 3