如何在nodejs中使用cheerio替换href值
How to replace the href value using cheerio in nodejs
我正在尝试替换 html 内容而非 working.How 的 href 值以使用 cheerio 并找到解决方案。
index.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>
app.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 文件中也写入该内容。希望能有所帮助。
我正在尝试替换 html 内容而非 working.How 的 href 值以使用 cheerio 并找到解决方案。
index.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>
app.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 文件中也写入该内容。希望能有所帮助。