我正在寻找一个正则表达式来隔离img的src值。(我知道这不是最好的方法,但在这种情况下我必须这样做)
我有一个字符串,其中包含简单的html代码,一些文本和一个图像。我需要从该字符串中获取src属性的值。到目前为止,我只成功地隔离了整个标记。
string matchString = Regex.Match(original_text, @"(<img([^>]+)>)").Value;
发布于 2010-11-23 23:10:47
string matchString = Regex.Match(original_text, "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;
发布于 2010-11-24 02:27:15
我知道你说你必须使用正则表达式,但是如果可能的话,我真的会给这个开源项目一个机会:HtmlAgilityPack
它真的很容易使用,我刚刚发现它,它对我帮助很大,因为我正在做一些更繁重的html解析。它基本上允许您使用XPATHS来获取元素。
他们的示例页面有点过时,但是API非常容易理解,如果您稍微熟悉一下xpath,您将很快了解它。
查询的代码应该类似于:(未编译的代码)
List<string> imgScrs = new List<string>();
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlText);//or doc.Load(htmlFileStream)
var nodes = doc.DocumentNode.SelectNodes(@"//img[@src]"); s
foreach (var img in nodes)
{
HtmlAttribute att = img["src"];
imgScrs.Add(att.Value)
}
发布于 2012-04-06 18:05:39
我尝试了弗朗西斯科·诺列加的建议,但看起来HtmlAgilityPack的api已经被修改了。下面是我解决这个问题的方法:
List<string> images = new List<string>();
WebClient client = new WebClient();
string site = "http://www.mysite.com";
var htmlText = client.DownloadString(site);
var htmlDoc = new HtmlDocument()
{
OptionFixNestedTags = true,
OptionAutoCloseOnEnd = true
};
htmlDoc.LoadHtml(htmlText);
foreach (HtmlNode img in htmlDoc.DocumentNode.SelectNodes("//img"))
{
HtmlAttribute att = img.Attributes["src"];
images.Add(att.Value);
}
https://stackoverflow.com/questions/4257359
复制相似问题