zek*_*kia 22 c# regex image src
我正在寻找一个正则表达式来隔离img的src值.(我知道这不是最好的方法,但这是我在这种情况下必须做的)
我有一个字符串,其中包含简单的HTML代码,一些文本和图像.我需要从该字符串中获取src属性的值.到目前为止,我只设法将整个标签隔离开来.
string matchString = Regex.Match(original_text, @"(<img([^>]+)>)").Value;
Run Code Online (Sandbox Code Playgroud)
Hin*_*nek 44
string matchString = Regex.Match(original_text, "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;
Run Code Online (Sandbox Code Playgroud)
Fra*_*ega 13
我知道你说你必须使用正则表达式,但如果可能的话我真的会给这个开源项目一个机会: 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)
}
Run Code Online (Sandbox Code Playgroud)
我尝试过Francisco Noriega建议的内容,但看起来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);
}
Run Code Online (Sandbox Code Playgroud)