0

有多种方法可以找到它,但我想以特定的方式做到这一点。这里是-

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

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

然后它执行-

查找(: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>

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

4

1 回答 1

1

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

我不知道您的环境,但是在带有 lxml 的 Python 中它可以工作:

>>> 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]")]')
[]
于 2013-07-20T11:56:26.163 回答