获取xpath的父级,通过子跨度搜索某个类

时间:2017-04-03 16:50:52

标签: javascript html xml xpath

我这里有html:

<div class="select-menu-item js-navigation-item">...</div>
<div class="select-menu-item js-navigation-item">...</div>
<div class="select-menu-item js-navigation-item">
    <svg ...></svg>

    <div class="select-menu-item-gravatar"></div>
    <div class="select-menu-item-text lh-condensed">
        <span class="select-menu-item-heading">
            the_username813
            <span class="description">Last name, First name</span>
        </span>
    </div>
</div>

我需要使用<div class="select-menu-item js-navigation-item">获取包含子范围的the_username813

我尝试了一些失败的事情,比如:

ipdb> element = self.driver.find_element_by_xpath("//span[contains(., 'the_username813')]/parent::div[contains(c
oncat(' ', @class, ' '), ' js-navigation-item ')]")
*** NoSuchElementException: Message: Unable to locate element: //span[contains(., 'the_username813')]/parent::div[contains(concat(' ', @class, ' '), ' js-navigation-item ')]

如何使用xpath获取此父div元素?谢谢

1 个答案:

答案 0 :(得分:1)

请尝试以下Xpath表达式并告诉我结果:

//div[@class="select-menu-item js-navigation-item" and .//span[normalize-space(text())="the_username813"]]

另请注意,<div class="select-menu-item js-navigation-item">不是直接parent,而是ancestor元素,因此您也可以使用

//span[normalize-space(text())="the_username813"]/ancestor::div[@class="select-menu-item js-navigation-item"]