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天前赞一波!
相关文章
- C# Word转换成Pdf的方法
- c#使用MongoDB开发LBS应用
- hprose for C#使用教程
- 使用htmlagilitypack+xpath抓取网页内容示例
- c#实现与Java无差异的GZip压缩和GZip解压缩
- .NET Core c#使用SkiaSharp压缩裁切图片去除水印
- c# decimal保留2位小数 并向下舍入
- .NET Core c#使用SkiaSharp压缩图片
- C#复制文件到指定文件夹
- c#获取枚举的Description
- c#读取pdf里的表格
- c# HttpClient下载图片
- c#获取文件夹所有文件列表
- c# int数值转enum枚举
- c#获取枚举的描述Description和摘要Summary
- .NET C#获取客户端真实IP
- c# 常用语法糖
- c# 爬虫组件有哪些?
- c#和f#的区别
- 自学.NET C#的中文网站推荐
文章评论
评论问答