【发布时间】:2013-07-29 08:41:39
【问题描述】:
我以编程方式下载了网页内容并将其保存在字符串变量中。查找“og:image”元标记内容网址的最佳方法是什么?
例如假设来自页面视图源的 sn-p 如下所示:
<meta property="og:site_name" content="The Christian Science Monitor" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://www.csmonitor.com/Business/2013/0729/Cannes-jewel-heist-53-million-in-diamonds-jewels-stolen-from-hotel" />
<meta property="og:description" content="Cannes jewel heist saw $53 million in diamonds and other precious gems stolen from a hotel on the French Riviera. The Cannes jewel heist is the latest in a series of several brazen jewelry thefts in Europe in recent years." />
<meta property="og:image" content="http://www.csmonitor.com/var/ezflow_site/storage/images/media/content/2013/0729-jewels/16474969-1-eng-US/0729-jewels.jpg" />
<meta property="og:title" content="Cannes jewel heist: $53 million in diamonds, jewels stolen from hotel" />
<meta name="sailthru.author" content="Thomas Adamson" />
我想提取作为“og:image”标签目标的“http://www.csmonitor.com/var/ezflow_site/storage/images/media/content/2013/0729-jewels/16474969-1-eng-US/0729-jewels.jpg”字符串。
我可以在代码中构造一些逻辑来查找子字符串,然后从那里获取它,但我想使用类似于此的正则表达式语法来完成此操作:
List<Uri> links = new List<Uri>();
string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
最后一个示例抓取网页源并提取所有图像标签。我想对 og:image 标签做同样的事情,但我不太精通正则表达式。
【问题讨论】:
-
不要使用正则表达式解析 HTML。使用适当的 HTML 解析模块。 您无法使用正则表达式可靠地解析 HTML,并且您将面临悲伤和挫败感。一旦 HTML 与您的期望发生变化,您的代码就会被破坏。
-
谢谢安迪。你能推荐一个合适的 HTML 解析模块吗?我在 C# 环境中。
-
对不起,我不能。我根本不了解 C# 世界。在 StackOverflow 或 Google 中搜索“html parsing C#”,看看你能找到什么。
标签: c# regex html-parsing