简体   繁体   中英

Replace the attribute value using cheerio

The following code is used to replace all the <img> tags src value. But the following code does not modify the original document. $.html prints the original document and not the modified one.

    $ = 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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