我希望能够抓取包含多个“<a href
”标签的网页并返回它们的结构化集合。
<div>
<p>Lorem ipsum... <a href="https://stackoverflow">Classic link</a>
<a title="test" href=http://sloppy-html-5-href.com>I lovez HTML 5</a>
</p>
<a class="abc" href='/my-tribute-to-javascript.html'>I also love JS</a>
<iframe width="420" height="315" src="http://www.youtube.com/embed/JVPT4h_ilOU"
frameborder="0" allowfullscreen></iframe><!-- Don't catch me! -->
</div>
所以我想要这些值:
- https://stackoverflow |经典链接
- http://sloppy-html-5-href.com |我喜欢 HTML 5
- /my-tribute-to-javascript.html |我也喜欢 JS
如您所见,应该只捕获“a href”中的值,标签中包含链接和内容。它应该支持所有 HTML 5 有效的 href。 href 属性可以用任何其他属性包围。
所以我基本上想要一个正则表达式来填充以下代码:
public IEnumerable<Tuple<string, string>> GetLinks(string html) {
string pattern = string.Empty; // TODO: Get solution from Stackoverflow
var matches = Regex.Matches(html, pattern);
foreach(Match match in matches) {
yield return new Tuple<string, string>(
match.Groups[0].Value, match.Groups[1].Value);
}
}
最佳答案
我一直读到用正则表达式解析 Html 是邪恶的。好吧……这肯定是真的……
但就像 Evil 一样,Regex 也很有趣 :)
所以我会尝试这个:
Regex r = new Regex(@"<a.*?href=(""|')(?<href>.*?)(""|').*?>(?<value>.*?)</a>");
foreach (Match match in r.Matches(html))
yield return new Tuple<string, string>(
match.Groups["href"].Value, match.Groups["value"].Value);
关于C# 正则表达式 : Getting URL and text from multiple "a href"-tags,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8048951/