Replace the attribute value using cheerio

和自甴很熟 提交于 2019-12-08 07:39:14

问题


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

回答1:


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">



回答2:


Use .attr('src', new_src) instead of .prop().



来源:https://stackoverflow.com/questions/36011918/replace-the-attribute-value-using-cheerio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!