【问题标题】:How to split tags from HTML如何从 HTML 中拆分标签
【发布时间】:2018-12-05 12:30:01
【问题描述】:

我有非常简单的 HTML 文本。在这里,我希望仅将图像附加到其他位置。如何使用 c# 单独剪切图像标签。

<p>this is new document<img alt="" height="150" src="https://kuba2storage.blob.core.windows.net/kuba-appid-1/manual-1203/images/desert-20180824203530071.jpg" width="200"/>This is new document</p>

我想从这个数据中单独获取img标签。例如

<img alt="" height="150" src="https://kuba2storage.blob.core.windows.net/kuba-appid-1/manual-1203/images/desert-20180824203530071.jpg" width="200"/>

代码:

var parts = Regex.Split(text.Text, @"(<img>[\s\S]+?<\/img>)").Where(l => l != string.Empty).ToArray();

【问题讨论】:

标签: c# tags


【解决方案1】:

您可以尝试使用像HtmlAgilityPack 这样的第三方库,他们的Example page 上有一些很好的例子,就是这样

using System;
using HtmlAgilityPack;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        GetLinks();
    }

    private static void GetLinks()
        {
            HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
            HtmlAgilityPack.HtmlDocument doc = hw.Load("https://www.ynet.co.il/home/0,7340,L-8,00.html");
            List<string> htmls = new List<string>();
            foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//img"))
            {
                string hrefValue = link.GetAttributeValue("src", string.Empty);
                htmls.Add(hrefValue);
            }
        foreach(var item in htmls){
        Console.WriteLine(item);
        }
        if(doc.DocumentNode.SelectNodes("//a[@href]")==null){
        Console.WriteLine("no links");
        }
        }
}

这个可以在https://dotnetfiddle.net/QAZnDz上找到,也可以用linq过滤图片等

【讨论】:

    【解决方案2】:

    你可以试试下面的

    using System.Collections.Generic;
    using System.Text.RegularExpressions;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void  Main(string[] args)
            {
                 string data = "<p>this is new document<img alt='' height='150' src='https://kuba2storage.blob.core.windows.net/kuba-appid-1/manual-1203/images/desert-20180824203530071.jpg' width='200'/>This is new document</p>";
                 var newdt = FetchImgsFromSource(data);
    
            }
        }
        public static List<string> FetchImgsFromSource(string htmlSource)
        {
            List<string> listOfImgdata = new List<string>();
            string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
            var matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            foreach (Match m in matchesImgSrc)
            {
                string href = m.Groups[1].Value;
                listOfImgdata.Add(href);
            }
            return listOfImgdata;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 2016-01-09
      相关资源
      最近更新 更多