html查找相同属性的值,c# – 遍历html字符串以查找所有img标记并替换src属性值

本文介绍如何利用HtmlAgilityPack库解析网页中的Base64编码图片,并将其转换为本地资源。通过示例代码展示如何抓取指定网页上的Base64图像,解码并替换src属性,适用于需要批量处理Base64图片的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果我正确理解您的需要,您可以使用HtmlAgilityPack来实现此目的.使用正则表达式可能会导致不必要的行为你能试试下面的代码吗?

public static string DoIt()

{

string htmlString = "";

using (WebClient client = new WebClient())

htmlString = client.DownloadString("http://dean.edwards.name/my/base64-ie.html"); //This is an example source for base64 img src, you can change this directly to your source.

HtmlDocument document = new HtmlDocument();

document.LoadHtml(htmlString);

document.DocumentNode.Descendants("img")

.Where(e =>

{

string src = e.GetAttributeValue("src", null) ?? "";

return !string.IsNullOrEmpty(src) && src.StartsWith("data:image");

})

.ToList()

.ForEach(x =>

{

string currentSrcValue = x.GetAttributeValue("src", null);

currentSrcValue = currentSrcValue.Split(',')[1];//Base64 part of string

byte[] imageData = Convert.FromBase64String(currentSrcValue);

string contentId = Guid.NewGuid().ToString();

LinkedResource inline = new LinkedResource(new MemoryStream(imageData), "image/jpeg");

inline.ContentId = contentId;

inline.TransferEncoding = TransferEncoding.Base64;

x.SetAttributeValue("src", "cid:" + inline.ContentId);

});

string result = document.DocumentNode.OuterHtml;

}

希望这可以帮助

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值