【问题标题】:Webdriver. How to retrieve the xpath of found element?网络驱动程序。如何检索找到的元素的 xpath?
【发布时间】:2014-06-27 18:44:54
【问题描述】:

我有一些代码可以根据可见文本查找元素。

# Defines the text I am looking for
productName = "customer x job"
#Finds the element I am looking for
inputElement = driver.find_element_by_xpath(".//*[@id='demo_top']/div/table[2]/tbody/tr/td[1]/ul/li[2]/ul/li[1]/a".format(productName))

我需要单击右侧的一个框。

元素的具体xpath为:

#What I just found
/html/body/div[1]/div/div/table[2]/tbody/tr/td[1]/ul/li[2]/ul/li[1]/a
#The box I actually want to click
/html/body/div[1]/div/div/table[2]/tbody/tr/td[1]/ul/li[2]/ul/li[1]/span/a

所以我只需要将“/span/a”添加到 inputElement 的 xpath 中。问题是,我不知道这个元素的具体 xpath。有没有办法让我将 inputElement 转换为特定的 xpath,所以我可以将“/span/a”附加到它的末尾并单击该元素?

编辑:好像我弄错了,我需要将最后的“a”替换为“span/a”

下面是html:

<li class="TCbullet">
<span>
<a class="editCategory " onclick="return hs.htmlExpand(this, { objectType: 'iframe' } );" href="cat-frame-category.php?categoryID=1340"> </a>  #I want to click this
<span class="sort">sort: 0</span>
</span>
<a class="anchorCategory" alt="Eden Cognitive Content" href="?ownerID=C518&g=1085&t=1340">Eden Cognitive Content</a>  # I have found this
</li>

我想访问editCategory 链接,我找到了anchorCategory 链接。

【问题讨论】:

    标签: python selenium xpath webdriver children


    【解决方案1】:

    你可以在你已经找到的元素上调用find_element_by_xpath()

    link = inputElement.find_element_by_xpath('./preceding-sibling::span/a')
    

    这将选择span 中的a 标记,该标记位于您找到的a 标记之后。

    【讨论】:

    • 谢谢!我没有意识到我能做到这一点。不过,我似乎对某些事情不正确,您也许可以提供帮助。看起来我错过了第一个 xpath 末尾有一个标签。有没有办法用 'span/a' 替换最后一个 'a' ?
    • @user3784334 能否请您显示相关的html,以便我确定html结构?谢谢。只需编辑问题并将其粘贴到那里。
    • @user3784334 好的,span/a 似乎在您找到的a 之前,编辑了答案 - 尝试使用preceding-sibling,应该可以。谢谢。
    猜你喜欢
    • 2015-12-27
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多