javascript - 如何在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);
}
});
}
});
解决方案
嘿@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 文件中编写它。希望这会有所帮助。
推荐阅读
- parallel-processing - 如何跨多个设备并行化简单操作?
- javascript - Javascript - 如何实现可覆盖的生命周期钩子
- javascript - 在 Symfony 4 中使用 WebPack Encore 定义 JavaScript 对象后无法识别
- bash - grep 在函数中不起作用
- javascript - SUM items in an Array
- sql-server - 没有默认颜色的 Management Studio
- android - 上传大视频文件块使用retrofit2 (Android)
- javascript - 无法使用 jQuery 动态添加表
- gnupg - gpg --with-colon returns ????-??-?? as the expiration date. Linux Y2K issue?
- java - how can i get EXPOSURE TIME when i take picture using camera2?