首页 > 解决方案 > 如何在nodejs中使用cheerio替换href值

问题描述

我正在尝试从 html 内容中替换 href 值但无法正常工作。如何为此使用cheerio 并找到解决方案。

索引.html:

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>
<div>
<a href="#" id="reset" class="reset">Link</a>
</div>

</body>
</html>

应用程序.js:

var cheerio = require("cheerio");
var fs = require('fs');

fs.readFile('./public/index.html', { encoding: 'utf-8' }, function(err, html) 
{
  if (err) {
      console.log(err);
  } else {
      const $ = cheerio.load(html); 
      $("a").each(function() {
          var id = $(this).attr("id");
          var url = "http://www.google.com";
          var new_href = encodeURIComponent(url);
          if (id == "reset") {
             $(this).attr("href", new_href);
          } 
      });
    }
});

              

标签: javascriptnode.jscheerio

解决方案


嘿@Pappa S 因为我检查了你的代码a标签值是替换。

var cheerio = require("cheerio");
var fs = require('fs');

fs.readFile('./public/index.html', { encoding: 'utf-8' }, function(err, html) {
  console.log(html)
if (err) {
    console.log(err);
  } else {
         const $ = cheerio.load(html); 
         $("a").each(function() {
          var id = $(this).attr("id");
          var url = "http://www.google.com";
          // var new_href = encodeURIComponent(url);
            if (id == "reset") {
               $(this).attr("href", url);
          }
          console.log($.html());
     });
  }
});

// 输出

<!DOCTYPE html><html><head></head><body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>
<div>
<a href="http://www.google.com" id="reset" class="reset">Link</a>
</div>


</body></html>

正如我所见,控制台值中的 html 代码已被替换。但是您还需要在 html 文件中编写它。希望这会有所帮助。


推荐阅读