简体   繁体   English

使用cheerio替换属性值

[英]Replace the attribute value using cheerio

The following code is used to replace all the <img> tags src value. 以下代码用于替换所有<img>标签的src值。 But the following code does not modify the original document. 但是以下代码不会修改原始文档。 $.html prints the original document and not the modified one. $.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();

You have a very small error, "src" in an img it's an attribute and not a property. 您有一个非常小的错误,img中的“ src”是属性而不是属性。

So this code will work: 因此,此代码将起作用:

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());

output is 输出是

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM