所以我有以下形式的html:
<html>
<head>
RANDOM JAVASCRIPT AND CSS AHHHHHH!!!!!!!!
</head>
<body>
<a href="/Random/link/here">Random</a>
<a href="/Random/link/here">Random</a>
<a href="/Random/link/here">Random</a>
<a href="/Random/link/here">Random</a>
<a href="/Random/link/here">Random</a>
<a href="/Random/link/here">Random</a>
<table class="table">
<tr><a href="/subdir/members/Name">Name</a></tr>
<tr><a href="/subdir/members/Name">Name</a></tr>
<tr><a href="/subdir/members/Name">Name</a></tr>
<tr><a href="/subdir/members/Name">Name</a></tr>
<tr><a href="/subdir/members/Name">Name</a></tr>
<tr><a href="/subdir/members/Name">Name</a></tr>
<tr><a href="/subdir/members/Name">Name</a></tr>
<tr><a href="/subdir/members/Name">Name</a></tr>
<tr><a href="/subdir/members/Name">Name</a></tr>
<tr><a href="/subdir/members/Name">Name</a></tr>
</table>
<body>
</html>
我有以下代码,创建的目的是提取 中包含的信息,然后从该信息中提取链接:
public class MainClass
{
public static void Main(String[] args)
{
string url = args[1];
Extractinfo pageScrape = new Extractinfo();
pageScrape.RenderPage(url);
}
}
public class Extractinfo
{
public HtmlDocument RenderPage(string url)
{
try
{
HtmlDocument pageSource = new HtmlDocument();
var webGet = new HtmlWeb();
pageSource = webGet.Load(url);
ExtractLinks(pageSource);
}
catch (WebException e)
{
Console.WrtieLine(e.Message + ": " + e.StackTrace);
}
}
private List<string> ExtractHrefTags(HtmlNode htmlSnippet)
{
List<string> hrefTags = new List<string>();
foreach (HtmlNode link in htmlSnippet.SelectNodes("//a[@href]"))
{
HtmlAttribute att = link.Attributes["href"];
hrefTags.Add(att.Value);
}
return hrefTags;
}
public void ExtractLinks(HtmlDocument pagesource)
{
var elements = pagesource.DocumentNode.SelectNodes("//table[@class='table']");
List<string> hrefTags = new List<string>();
foreach (var ele in elements)
{
hrefTags = ExtractHrefTags(ele);
}
}
}
}
现在,<table class="table>*****</table>
这段代码将页面上的所有链接都放入 List hreftags 中,而不是只获取位于 中的链接。我在这里做错了什么?如何修复错误,以便提取的唯一链接是其中的链接<table class="table>*****</table>
?
谢谢您的帮助!