使用 cheerio 替换属性值

Replace the attribute value using cheerio

本文关键字:属性 替换 cheerio 使用      更新时间:2023-09-26

以下代码用于替换所有<img>标记src值。但以下代码不会修改原始文档。 $.html打印原始文档,而不是修改后的文档。

    $ = cheerio.load(data);
    $("img").each(function() {
        var old_src=$(this).attr("src");
        var new_src = "/my_cached_image?url=" + encodeURIComponent(old_src);        
        $(this).prop("src", new_src);
    });
    modified_data = $.html();

你有一个非常小的错误,IMG 中的"src"是一个属性而不是属性。

所以这段代码将起作用:

var cheerio = require("cheerio");
var data = "<img src='yahoo.com'/>"
$ = cheerio.load(data);
$("img").each(function() {
        var old_src=$(this).attr("src");
        var new_src = "/my_cached_image?url=" + encodeURIComponent(old_src);
        console.log(new_src);
        $(this).attr("src", new_src);            
});
console.log($.html());

输出为

<img src="/my_cached_image?url=yahoo.com">

使用 .attr('src', new_src) 而不是 .prop()