Capybara,rspec-如何在页面的任何地方查找文本

时间:2013-07-20 10:52:27

标签: xpath capybara

有多种方法可以找到它,但我希望以特定方式执行此操作。这是 -

为了获得一个包含一些文本的元素,我的框架以这种方式创建了一个xpath -

@xpath =“// h1 [contains(text(),'[the-text-i-am-searching-for]')]”

然后执行 -

find(:xpath,@ xpath).visible?

现在我以类似的格式创建一个xpath,它只是在页面的任何地方查找文本,然后可以在find(:xpath,@ xpath).visible中使用?返回真或假。

提供更多背景信息: 我的HTML段落看起来像这样 -

<blink><p>some text here <b><u>some bold and underlined text here</u></b> again some text <a   href="www.link">Learn more</a> [the-text-i-am-searching-for]</p></blink>

但是如果我尝试使用我的xpath所在的find(:xpath,@ xpath)找到它 @xpath =“// p [contains(text(),'[the-text-i-am-searching-for]')]” 它失败了。

1 个答案:

答案 0 :(得分:1)

尝试将"//p[contains(text(), '[the-text-i-am-searching-for]')]"替换为"//p[contains(., '[the-text-i-am-searching-for]')]"

我不知道你的环境,但在Python中使用lxml它可以工作:

>>> import lxml.etree
>>> doc = lxml.etree.HTML("""<blink><p>some text here <b><u>some bold and underlined text here</u></b> again some text <a   href="www.link">Learn more</a> [the-text-i-am-searching-for]</p></blink>""")
>>> doc.xpath('//p[contains(text(), "[the-text-i-am-searching-for]")]')
[]
>>> doc.xpath('//p[contains(., "[the-text-i-am-searching-for]")]')
[<Element p at 0x1c1b9b0>]
>>> 

上下文节点.将转换为字符串以匹配签名boolean contains(string, string)http://www.w3.org/TR/xpath/#section-String-Functions

>>> doc.xpath('string(//p)')
'some text here some bold and underlined text here again some text Learn more [the-text-i-am-searching-for]'
>>> 

考虑这些变化

>>> doc.xpath('//p')
[<Element p at 0x1c1b9b0>]

>>> doc.xpath('//p/*')
[<Element b at 0x1e34b90>, <Element a at 0x1e34af0>]

>>> doc.xpath('string(//p)')
'some text here some bold and underlined text here again some text Learn more [the-text-i-am-searching-for]'

>>> doc.xpath('//p/text()')
['some text here ', ' again some text ', ' [the-text-i-am-searching-for]']

>>> doc.xpath('string(//p/text())')
'some text here '

>>> doc.xpath('//p/text()[3]')
[' [the-text-i-am-searching-for]']

>>> doc.xpath('//p/text()[contains(., "[the-text-i-am-searching-for]")]')
[' [the-text-i-am-searching-for]']

>>> doc.xpath('//p[contains(text(), "[the-text-i-am-searching-for]")]')
[]