请帮助我使用正则表达式从下面的示例 html 中找到 Favicon url。它还应检查文件扩展名“.ico”。我正在开发一个个人书签网站,我想保存我添加书签的链接的图标。我已经编写了将图标转换为 gif 并保存的 c# 代码,但我对正则表达式的了解非常有限,因此我无法选择此标签,因为不同站点的结束标签不同。结束标签示例 "/>""/link>"
我的编程语言是C#
<meta name="description" content="Create 360 degree rotation product presentation online with 3Dbin. 360 product pics, object rotationg presentation can be created for your website at 3DBin.com web service." />
<meta name="robots" content="index, follow" />
<meta name="verify-v1" content="x42ckCSDiernwyVbSdBDlxN0x9AgHmZz312zpWWtMf4=" />
<link rel="shortcut icon" href="http://3dbin.com/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="http://3dbin.com/css/1261391049/style.min.css" />
<!--[if lt IE 8]>
<script src="http://3dbin.com/js/1261039165/IE8.js" type="text/javascript"></script>
<![endif]-->
解决方案:另一种方法 下载并添加对 htmlagilitypack dll 的引用。谢谢你帮助我。我真的很喜欢这个网站:)
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(readcontent);
if (doc.DocumentNode != null)
{
foreach (HtmlNode link in doc.DocumentNode.SelectNodes(@"//link[@href]"))
{
HtmlAttribute att = link.Attributes["href"];
if (att.Value.EndsWith(".ico"))
{
faviconurl = att.Value;
}
}
}
最佳答案
这应该匹配包含 href=http://3dbin.com/favicon.ico 的整个链接标签
<link .*? href="http://3dbin\.com/favicon\.ico" [^>]* />
根据您的评论更正:
我看到您有一个 C# 解决方案 太棒了!但是以防万一您仍然想知道是否可以使用正则表达式来完成,下面的表达式可以满足您的要求。比赛的第 1 组将只有 url。
<link .*? href="(.*?.ico)"
使用它的简单 C# 片段:
// this is the snipet from your example with an extra link item in the form <link ... href="...ico" > ... </link>
//just to make sure it would pick it up properly.
String htmlText = String htnlText = "<meta name=\"description\" content=\"Create 360 degree rotation product presentation online with 3Dbin. 360 product pics, object rotationg presentation can be created for your website at 3DBin.com web service.\" /><meta name=\"robots\" content=\"index, follow\" /><meta name=\"verify-v1\" content=\"x42ckCSDiernwyVbSdBDlxN0x9AgHmZz312zpWWtMf4=\" /><link rel=\"shortcut icon\" href=\"http://3dbin.com/favicon.ico\" type=\"image/x-icon\" /><link rel=\"shortcut icon\" href=\"http://anotherURL/someicofile.ico\" type=\"image/x-icon\">just to make sure it works with different link ending</link><link rel=\"stylesheet\" type=\"text/css\" href=\"http://3dbin.com/css/1261391049/style.min.css\" /><!--[if lt IE 8]> <script src=\"http://3dbin.com/js/1261039165/IE8.js\" type=\"text/javascript\"></script><![endif]-->";
foreach (Match match in Regex.Matches(htmlText, "<link .*? href=\"(.*?.ico)\""))
{
String url = match.Groups[1].Value;
Console.WriteLine(url);
}
将以下内容打印到控制台:
http://3dbin.com/favicon.ico
http://anotherURL/someicofile.ico
关于c# - 正则表达式从网页中提取 Favicon url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6556141/