华廷:当发现文字,我怎么给它包含元素的引用? [英] WatiN: When finding text, how do I get a reference to its containing element?

查看:97
本文介绍了华廷:当发现文字,我怎么给它包含元素的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下HTML页面:

 < HTML和GT; 
< HEAD>
<标题>华廷测试与LT; /标题>
< /头>
<身体GT;
< DIV>
< P>的Hello World<!/ P>
< / DIV>
< /身体GT;
< / HTML>



我希望能够寻找一些文字(可以说世界),并获得它的父元素的引用(在这种情况下,< p> 元素)






如果我试试这个:

  VAR元素= ie.Element(Find.ByText(T => t.Contains(世界)))

或本:

  VAR元素= ie.Element(E => e.Text = NULL&放大器;&放; e.Text.Contains(世界)); 



我找回了< HTML> 元件。这是与华廷文档 Element.Text 其中规定是一致的:获取此元素的InnerText(并包含在此元素的所有元素的InnerText)



由于页面中的所有文字都包含在< HTML> 元素,我会永远把它恢复,而不是直接父。






有没有办法让正下方只是文本一个元素(而不是由它包含的元素中的文本)?



有没有这个做什么?



的另一种方式< 。p>非常感谢


解决方案

娄代码将找到<内部第一个元素;车身/> 中含World文本。这些被列为元素容器和具有子元素将被省略元素

  VAR元素= ie.ElementOfType<车身及GT;(查找。。首先())机构(E => 
{
如果(e.Text = NULL&放大器;!&安培; e.Text.Contains(世界))
$ { b $ b VAR容器= E为IElementContainer;
如果(集装箱== NULL || container.Elements.Count == 0)
返回真;
}
返回FALSE;
});

注意的:你可能想知道为什么我写了 ie.ElementOfType<车身方式>(Find.First())元素,而不是仅仅 ie.Element 。这应该工作,但事实并非如此。我认为这是一个错误。我写这件事华廷邮件列表上后,当我收到的答案会更新这个答案。


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.

解决方案

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.

var element = ie.ElementOfType<Body>(Find.First()).Element(e =>
{
    if (e.Text != null && e.Text.Contains("World"))
    {
        var container = e as IElementContainer;
        if (container == null || container.Elements.Count == 0)
            return true;
    }
    return false;
});

Note: You may wonder why I wrote ie.ElementOfType<Body>(Find.First()).Element instead of just ie.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.

这篇关于华廷:当发现文字,我怎么给它包含元素的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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