如何解析HTML字符串以获取图片标签中的SRC信息?

26

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

根据这个问题,XPath比正则表达式更好。

有人知道如何在C#中实现这个吗?

4个回答

57
如果您的输入字符串是有效的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());
    }
}

谢谢你,我一直在为自己的正则表达式苦恼! - Dave Harding
1
如果 href 包含空格,([^'"" >]+?) 就无法工作! - Ahmad
using( StreamReader sr = new StreamReader( response.GetResponseStream() ) 这一行缺少一个额外的闭合括号。 - Kaitlyn

11
任何HTML解析的大问题在于“格式正确”这一部分。你已经看到了那些糟糕的HTML - 其中有多少实际上是格式正确的呢?我需要做类似的事情 - 解析出文档中的所有链接(在我的情况下)并使用重写后的链接进行更新。我在CodePlex上找到了Html Agility Pack。它非常出色(并且可以处理格式不正确的HTML)。
以下是迭代文档中链接的代码片段:
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
    }
}

原始博客文章


4

如果您只需要图片,我建议您使用正则表达式。类似这样的表达式应该可以解决问题:

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

-3
如果它是有效的XHTML,你可以这样做:
XmlDocument doc = new XmlDocument();
doc.LoadXml(html);
XmlNodeList results = doc.SelectNodes("//img/@src");

祝你好运,尝试将90%的HTML页面加载到XmlDocument中 :) - axel_c
已经尝试过了,HTML 不是有效的 XML,因此会抛出异常。 - Roberto Bonini
@RobertoBonini 你是个专家! - Snickbrack

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接