1. 程式人生 > >selenium 查詢父子節點和兄弟節點

selenium 查詢父子節點和兄弟節點

<html>
<body>
<div id="parent">
    parent
    <div id="A"> old brother</div>
    <div id="B"> child</div>
    <div id="C"> litter brother</div>
</div>
</body>
</html>

這裡我主要介紹xpath,我認為這個最好用,通用

父查子

print driver.find_element_by_xpath("//div[@id='parent']/div[2]").text  #child
print driver.find_element_by_xpath("//div[@id='parent']/div[@id='B']").text  #child

子查父

print driver.find_element_by_xpath("//div[@id='B']/..").text #parent

定位兄弟節點

print driver.find_element_by_xpath("//div[@id='B']/../div[1]").text #old brother
print driver.find_element_by_xpath("//div[@id='B']/../div[3]").text #litter brother