Cheerio 在脚本标签中查找文本

yoz*_*ama 3 javascript node.js cheerio

我想提取脚本标签中的js脚本。

这是脚本标签:

<script>
  $(document).ready(function(){

    $("#div1").click(function(){
      $("#divcontent").load("ajax.content.php?p=0&cat=1");
    });

    $("#div2").click(function(){
      $("#divcontent").load("ajax.content.php?p=1&cat=1");
    });

  });
</script>
Run Code Online (Sandbox Code Playgroud)

我有一个像这样的 ids 数组['div1', 'div2'],我需要提取其中的 url 链接:所以如果我调用一个函数:

getUrlOf('div1');
Run Code Online (Sandbox Code Playgroud)

它会返回ajax.content.php?p=0&cat=1

rya*_*nza 6

如果您使用的是较新版本的cheerio (1.0.0-rc.2),则需要使用.html()而不是.text()

const cheerio = require('cheerio');
const $ = cheerio.load('<script>script one</script>  <script>  script two</script>');

// For the first script tag
console.log($('script').html());

// For all script tags
console.log($('script').map((idx, el) => $(el).html()).toArray());

Run Code Online (Sandbox Code Playgroud)

https://github.com/cheeriojs/cheerio/issues/1050