簡體   English   中英

XPath:選擇包含規范化文本的節點,不包括祖先節點

[英]XPath: select node that contains normalized text, excluding ancestor nodes

我正在尋找一個高性能的通用查詢來選擇“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-if-you-could (盡管它的名稱)的div元素,並且選擇帶有注釋字符串的最深元素值,那么:

  1. 向上述 XPath 添加一個額外的謂詞。
  2. 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-onediv

結束了這個

//*[         contains(normalize-space(.), 'The quick brown fox jumped over the lazy dog.') ]
   [not(.//*[contains(normalize-space(.), 'The quick brown fox jumped over the lazy dog.') ])]

$x("//*[contains(normalize-space(.), 'The quick brown fox jumped over the lazy dog.')][not(.//*[contains(normalize-space(.), 'The quick brown fox jumped over the lazy dog.') ])]")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM