使用Selenium WebDriver查找任何给定元素的下一个同级 [英] Find next sibling of any given element with Selenium WebDriver

查看:1126
本文介绍了使用Selenium WebDriver查找任何给定元素的下一个同级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个给定WebElement的方法来查找并返回下一个元素.我已经找到了很多有关将XPath与"following"或"following-sibling"一起使用的示例,但是我无法使其正常工作.出于此问题的目的,我将显示html,但是元素类型与我所需的内容无关,因为我想要一个通用方法,该方法给出给定任何类型的任何元素(a/ul/div/任何),它将返回下一个兄弟,无论类型如何.

I'm trying to create a method that given a WebElement finds and returns the very next element. I have found a lot of examples for what should work using XPath with "following" or "following-sibling" but I can't get it to work. For the purpose of the question here I will show the html, but the element types are irrelevant for what I need as I want a generic method that given any element of any type (a/ul/div/whatever) it will return the next sibling regardless of type.

<a id="blah" href="#" class="stuff">"My Label"</a>
<ul class="some-class">
    <li>...</li>
    <li>...</li>
</ul>

我的越野车调试代码:

IWebElement element = driver.FindElement(By.Id("blah"));
IWebElement nextElement = element.FindElement(By.XPath("//following-sibling::ul[@class='some-class']"));

我怀疑我的xpath语法是错误的...而且我坦率地说是毫无头绪的. "//"是相对于元素还是相对于DOM本身?有一种不知道下一个元素的标签是什么的方法吗?无论它是什么类型,我都只想获取下一个元素.我只是想找出最简单,最通用的方法.我想拥有的东西:

I suspect my xpath syntax is wrong... and I am frankly clueless. Does the "//" mean relative to element or to the DOM itself? Is there a way of doing this without knowing what the tag of the next element is? I would like to just get the next element no matter what type it is. I'd just like to figure out the simplest and most generic way to do this. What I would like to have:

public IWebElement NextSibling(IWebElement element) 
{
    IWebElement nextSibling = element.FindElement(By.?("magical string to find next sibling"));
    return nextSibling;
}

...这正是您可以使用element.nextSibling()

...which is exactly what you can already do in javascript with element.nextSibling()

推荐答案

在xpath中尝试使用.//,因为这是相对路径,您使用的是绝对路径,所以它无法按预期工作.

Try with .// in your xpath because that is relative path, you were using absolute path so it's not working as you expected.

这篇关于使用Selenium WebDriver查找任何给定元素的下一个同级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆