我正在寻找一个高性能的通用查询来选择“The quick brown fox jumped over the lazy dog”。类似于简单的 CMD+C 复制文本的方式。
看来我需要使用 textContent
,但我的 XPath 也在选择祖先(直到主体),而不仅仅是第一个(少数)祖先。如何限制范围?
示例 node.textContent
"
The
quick brown fox
jumped over the
lazy dog.
"
运行代码片段 → 整页 → 按照说明操作
<div id='dont-select-this' style='text-align:center'>
<div id='dont-select-this-but-it-would-be-cool-if-you-could' style='background:lightgreen;'>
<div id='select-this-one'>
<p>
<span>The</span>
<em>quick brown fox</em>
<span>jumped over the</span>
</p>
<p>
lazy<span> </span><b>dog.</b>
</p>
</div>
</div>
<hr>
<div>open chrome devtools → console</div>
<div>change frame (see below)</div>
<div>type <code>$x('//*[contains(., "quick brown fox")]')</code></div>
<hr>
<img alt='select chrome devtools frame' height=300 src='https://i.imgur.com/L1MhCY8.png'/>
</div>
最佳答案
这个 XPath,
//div[normalize-space() = 'The quick brown fox jumped over the lazy dog.']
仅选择具有以下 @id
值的两个 div
元素,
dont-select-this-but-it-would-be-cool-if-you-could
select-this-one
根据要求。
如果您真的想排除 id
值为 dont-select-this-but-it-would-be-cool- 的
(尽管它的名字)并且仅选择具有指定字符串值的最深元素,然后:div
元素if-you-could
- 向上述 XPath 添加附加谓词。
- 将
div
更改为*
。
总计:
//*[ normalize-space() = 'The quick brown fox jumped over the lazy dog.' ]
[not(.//*[normalize-space() = 'The quick brown fox jumped over the lazy dog.' ])]
这只会选择 id
属性值为 select-this-one
的 div
。
关于javascript - XPath:选择包含规范化文本的节点,不包括祖先节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59447945/