繁体   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