WatiN:查找文本时,如何获取对其包含元素的引用?
给定以下 HTML 页面:
<html>
<head>
<title>WatiN Test</title>
</head>
<body>
<div>
<p>Hello World!</p>
</div>
</body>
</html>
我希望能够搜索一些文本(假设 "World"
),并获取对其父元素的引用(在本例中为 <; p>
元素)。
如果我尝试这个:
var element = ie.Element(Find.ByText(t => t.Contains("World")))
或这个:
var element = ie.Element(e => e.Text != null && e.Text.Contains("World"));
我会返回 元素。这与
Element.Text
的 WatiN 文档一致,其中指出:“获取此元素的内部文本(以及此元素中包含的所有元素的内部文本)”。
由于页面中的所有文本都包含在 元素中,因此我始终会获取该文本而不是直接父元素。
有没有办法只获取元素正下方的文本(而不是元素包含的元素内的文本)?
还有另一种方法可以做到这一点吗?
非常感谢。
Given the following HTML page:
<html>
<head>
<title>WatiN Test</title>
</head>
<body>
<div>
<p>Hello World!</p>
</div>
</body>
</html>
I would like to be able to search for some text (lets say "World"
), and get a reference to its parent element (in this case the <p>
element).
If I try this:
var element = ie.Element(Find.ByText(t => t.Contains("World")))
or this:
var element = ie.Element(e => e.Text != null && e.Text.Contains("World"));
I get back the <html>
element. This is consistent with the WatiN documentation for Element.Text
which states: "Gets the innertext of this element (and the innertext of all the elements contained in this element)".
Since all text within the page is contained within the <html>
element, I'll always get this back instead of the immediate parent.
Is there a way to get just the text immediately beneath an element (not the text within the elements contained by it)?
Is there another way of doing this?
Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 Find.BySelector
You could use Find.BySelector
下面的代码将找到
内的第一个元素,其文本包含“World”。被分类为元素容器并具有子元素的元素将被省略。
注意:您可能想知道为什么我写了
ie.ElementOfType(Find.First()).Element
而不是只写ie.Element
。这应该有效,但事实并非如此。我认为这是一个错误。我在 WatiN 邮件列表上写了一篇关于它的文章,当我收到答案时会更新这个答案。Bellow code will find first element inside the
<body/>
with text containing "World". Elements which are classified as element containers and has child elements will be omitted.Note: You may wonder why I wrote
ie.ElementOfType<Body>(Find.First()).Element
instead of justie.Element
. This should work, but it doesn't. I think it's a bug. I wrote a post about it on WatiN mailing list and will update this answer when I receive the answer.我已经想出了一些可行的方法,但它有点老套而且效率很低。
这本质上是基于最深的包含元素将具有最短的
InnerHtml
。也就是说,包含直接父级的所有其他元素也将包含它的 HTML,因此会更长!I've come up with something that works, but it's a bit hacky and very inefficient.
This essentially works on the basis that the deepest containing element will have the shortest
InnerHtml
. That is, all other elements which contain the immediate parent will include it's HTML as well, and therefore be longer!