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

根据此问题 XPath优于正则表达式。

任何人都知道如何在C#中执行此操作?

有帮助吗?

解决方案

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

其他提示

任何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
    }
}

原创博文

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

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

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

XmlDocument doc = new XmlDocument();
doc.LoadXml(html);
XmlNodeList results = doc.SelectNodes("//img/@src");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top