如何使用内部文本获取元素(Watir、Nokogir、Hpricot)
我一直在用 Watir、Nokogir 和 Hpricot 进行实验。所有这些都使用自上而下的方法,这是我的问题。即他们使用元素类型来搜索元素。我想在不知道元素类型的情况下使用文本找出元素。 例如,
<element1>
<element2> Text2 </element2>
<element3> Text3 </element3>
text4
</element1>
我想要通过搜索 Text2 和 Text3 来获取 element2 和 element1 等。
请注意,我不知道元素是 div、tr/tds 还是链接等。我只知道文本。算法应该是这样的: 迭代所有元素,匹配内部文本,如果匹配则获取元素和父元素。
让我知道这是否有可能?
I have been expeirmenting with Watir, Nokogir and Hpricot. All of these use top->down approach which is my problem. i.e. they use element type to search element. I want to find out the element using the text without knowing element type.
e.g.
<element1>
<element2> Text2 </element2>
<element3> Text3 </element3>
text4
</element1>
I want is to get element2 and element1 etc by searching for Text2 and Text3.
Please note that I do not know if elements are divs or tr/tds or links etc. I just know the text. Algorithem should be something like :
iterated through all the elements, match inner text, if match get me the element and the parent element.
Let me kow if this is possible in any way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我没有完整的答案,但您可以使用 wiki(请参阅搜索内部 HTML)。
将返回
然后您可以迭代这些并检查它们是否是实际元素:
将返回
true
。而[1]
将返回false
。但是,如果您试图查找text4
,因为它返回:即不是实际的元素, 那么就会出现问题。所以也许在这些实例中(我不知道你如何确定这些实例)你可以检查它是否是一个元素,如果为 false 则得到父元素
抱歉我没有完整的答案,但认为“text()”的事情现在值得一提。
I don't have a complete answer, but you can use the text() functionality, outlined in the wiki (See Searching Inner HTML).
will return
You could then iterate through these and check they are actual elements:
Would return
true
. Whereas[1]
would returnfalse
. However, where this falls down is if you were trying to findtext4
as this returns:i.e. not the actual element. So perhaps in these instances (how you determine these instances I don't know) you could check whether it's an element, and if false get the parent
Sorry I don't have a complete answer, but thought the "text()" thing would be worth mentioning for now.
Watir 有 XPath 支持。我不太熟悉 XPath,但我很确定它可以满足您的需要。例如:
我还建议将您的问题发布到 watir-general。
Watir has XPath support. I am not really familiar with XPath but I am pretty sure it would do what you need. Something like:
I would also suggest posting your question at watir-general.