雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

c#使用HtmlAgilityPack编辑html并保存

2024-10-10 16

最近发现新博客里的图片忘记加alt属性了,为了搜索引擎优化决定为所有的文章内的图片添加alt属性,属性值为文章标题。

如果用正则表达式匹配比较头疼,还要考虑添加alt属性后保存。所以想到了抓取网页时使用的HtmlAgilityPack,可以读取属性然后判断元素是否拥有alt属性,如果拥有则不处理,否则添加属性。修改元素后通过htmlDocument.DocumentNode.InnerHtml可以得到修改后的html,相当方便。下面是实现的代码。

var articles = coupeFansContext.Articles.Where(x=>x.IsDeleted==false).OrderByDescending(x=>x.Id).ToList();
        foreach (var article in articles)
        {
            HtmlAgilityPack.HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument();
            htmlDocument.LoadHtml(article.ArticleContent);
            var imgs = htmlDocument.DocumentNode.SelectNodes("//img");
            if (imgs != null)
            {
                bool needSave = false;
                foreach (var img in imgs)
                {
                    var alt = img.GetAttributeValue("alt", string.Empty);
                    if (string.IsNullOrWhiteSpace(alt))
                    {
                        img.SetAttributeValue("alt", article.Title);
                        needSave = true;
                    }
                    var title = img.GetAttributeValue("title", string.Empty);
                    if (string.IsNullOrWhiteSpace(title))
                    {
                        img.SetAttributeValue("title", article.Title);
                        needSave = true;
                    }
                }
                if (needSave)
                {
                    article.ArticleContent = htmlDocument.DocumentNode.InnerHtml;
                    var rst = coupeFansContext.SaveChanges();
                }
            }
        }
更新于:8天前
赞一波!

文章评论

评论问答