簡體   English   中英

使用 jquery 或 cheerio 在兩個標簽之間查找 html 文本

[英]Find html text between two tags using jquery or cheerio

我認為這會相當簡單,但實際上沒什么用。 我在 node.js 中使用 cheerio 寫這篇文章。基本上,我有以下 HTML

<h2 id="understanding-adc">
<a class="anchor" href="#understanding-adc" aria-hidden="true"><span class="octicon octicon-link"></span></a>Understanding ADC</h2>

<p>test</p>

<ol>
  <li>test</li>
  <li>test</li>
  <li>Optimization</li>
</ol>

<h2 id="data-switching">
<a class="anchor" href="#data-switching" aria-hidden="true"><span class="octicon octicon-link"></span></a>Data switching</h2>

<p>test test.</p>

所以場景會是這樣的。 如果我傳遞 h2 標簽 id 讓我們說“#understanding-adc”,我需要獲取“#understanding-adc”和下一個 h2 標簽“#data-switching”之間的內容。 在這里,我知道我需要將哪個 h2 標簽傳遞給 function,而不是第二個。

我正在尋找的結果是這樣的:

<h2 id="understanding-adc">
    <a class="anchor" href="#understanding-adc" aria-hidden="true"><span class="octicon octicon-link"></span></a>Understanding ADC</h2>
    
    <p>test</p>
    
    <ol>
      <li>test</li>
      <li>test</li>
      <li>Optimization</li>
    </ol>

請幫我

首先 select 起始<h2> ,然后使用nextUntil()到達結尾<h2> ,調用addBack()將第一個h2元素放回結果中, wrapAll()將您感興趣的塊分區,並用parent()html()獲取它的 HTML 。

const cheerio = require("cheerio"); // 1.0.0-rc.12

const html = `
<h2 id="understanding-adc">
<a class="anchor" href="#understanding-adc" aria-hidden="true"><span class="octicon octicon-link"></span></a>Understanding ADC</h2>

<p>test</p>

<ol>
  <li>test</li>
  <li>test</li>
  <li>Optimization</li>
</ol>

<h2 id="data-switching">
<a class="anchor" href="#data-switching" aria-hidden="true"><span class="octicon octicon-link"></span></a>Data switching</h2>

<p>test test.</p>
`;
const $ = cheerio.load(html);

// make sure we're in a container
$("body").children().wrapAll("<div></div>");

const htmlOut = $("#understanding-adc")
  .nextUntil("h2")
  .addBack()
  .wrapAll("div")
  .parent()
  .html();
console.log(htmlOut);

暫無
暫無

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

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