2013-07-20 13 views
0

有多種方式可以找到它,但我想以特定的方式做到這一點。這是 -水豚,rspec-如何在頁面上的任何地方找到文本

要獲得與它的一些文本的元素,我的框架創建這個方式之

@xpath =「// H1 [的XPath包含(文本(),「[該文-i-AM-搜索換]')]」

然後executes-

發現(:XPath中,@xpath)。可見?

現在以類似的格式,我想創建一個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中,@xpath)在我的XPath是 @xpath =「// p [包含(text(),'[the-text-i-am-searching-for]')]」 它失敗。

+0

給出正確的html相關部分,你提供的部分不足以幫助你。 –

回答

1

嘗試用"//p[contains(., '[the-text-i-am-searching-for]')]"

更換"//p[contains(text(), '[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]")]') 
[] 
+0

謝謝,// p/*似乎是我正在尋找的東西,我會嘗試一下並更新結果。 – user2289202

+0

是的,它的工作。非常感謝! – user2289202