【问题标题】:How do you parse an HTML string for image tags to get at the SRC information?如何解析图像标签的 HTML 字符串以获取 SRC 信息?
【发布时间】:2010-09-13 10:08:07
【问题描述】:

目前我使用 .Net WebBrowser.Document.Images() 来执行此操作。它需要Webrowser 来加载文档。它很乱,占用资源。

根据this question XPath 在这方面比正则表达式更好。

有人知道如何在 C# 中做到这一点吗?

【问题讨论】:

    标签: c# .net html regex xpath


    【解决方案1】:

    如果您的输入字符串是有效的 XHTML,您可以将其视为 xml,将其加载到 xmldocument 中,然后执行 XPath 魔术 :) 但并非总是如此。

    否则你可以试试这个函数,它会返回来自 HtmlSource 的所有图片链接:

    public List<Uri> FetchLinksFromSource(string htmlSource)
    {
        List<Uri> links = new List<Uri>();
        string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
        MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        foreach (Match m in matchesImgSrc)
        {
            string href = m.Groups[1].Value;
            links.Add(new Uri(href));
        }
        return links;
    }
    

    你可以这样使用它:

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
    request.Credentials = System.Net.CredentialCache.DefaultCredentials;
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        using(StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            List<Uri> links = FetchLinksFromSource(sr.ReadToEnd());
        }
    }
    

    【讨论】:

    • 谢谢你,我正在用我自己的正则表达式敲我的头!
    • 如果 href 包含空格,([^'"" &gt;]+?) 不起作用!
    • using( StreamReader sr = new StreamReader( response.GetResponseStream() ) 行缺少一个额外的右括号。
    【解决方案2】:

    任何 HTML 解析的大问题是“格式良好”的部分。您已经看到了那里的废话 HTML - 其中有多少是格式正确的?我需要做类似的事情 - 解析文档中的所有链接(在我的情况下)用重写的链接更新它们。我在 CodePlex 上找到了Html Agility Pack。它摇摆不定(并处理格式错误的 HTML)。

    这是一个用于迭代文档中链接的 sn-p:

    HtmlDocument doc = new HtmlDocument();
    doc.Load(@"C:\Sample.HTM");
    HtmlNodeCollection linkNodes = doc.DocumentNode.SelectNodes("//a/@href");
    
    Content match = null;
    
    // Run only if there are links in the document.
    if (linkNodes != null)
    {
        foreach (HtmlNode linkNode in linkNodes)
        {
            HtmlAttribute attrib = linkNode.Attributes["href"];
            // Do whatever else you need here
        }
    }
    

    Original Blog Post

    【讨论】:

      【解决方案3】:

      如果您只需要图像,我会使用正则表达式。像这样的东西应该可以解决问题:

      Regex rg = new Regex(@"<img.*?src=""(.*?)""", RegexOptions.IgnoreCase);
      

      【讨论】:

        【解决方案4】:

        如果它是有效的 xhtml,你可以这样做:

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(html);
        XmlNodeList results = doc.SelectNodes("//img/@src");
        

        【讨论】:

        • 祝你好运,将 90% 的 html 页面加载到 XmlDocument 中:)
        • 已经试过了。 HTML 不是有效的 XML。从而引发异常。
        • @RobertoBonini 你是专家!
        猜你喜欢
        • 2016-11-21
        • 1970-01-01
        • 2019-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多