我正在尝试创建一个仅返回网站链接的搜寻器,并且使它返回HTML脚本。 我现在想使用if语句检查字符串是否返回,如果返回,它将搜索所有“ ”标签并向我显示href链接。 但我不知道要检查哪个对象或应该检查的值。
这是我到目前为止所拥有的:
namespace crawler
{
class Program
{
static void Main(string[] args)
{
System.Net.WebClient wc = new System.Net.WebClient();
string WebData wc.DownloadString("https://www.abc.net.au/news/science/");
Console.WriteLine(WebData);
// if
}
}
}
答案 0 :(得分:2)
您可以查看HTML Agility Pack:
然后,您可以从网页中找到所有链接,例如:
var hrefs = new List<string>();
var hw = new HtmlWeb();
HtmlDocument document = hw.Load(/* your url here */);
foreach(HtmlNode link in document.DocumentNode.SelectNodes("//a[@href]"))
{
HtmlAttribute attribute = link.Attributes["href"];
if (!string.IsNullOrWhiteSpace(attribute.Value))
hrefs.Add(attribute.Value);
}
答案 1 :(得分:0)
首先,您可以创建一个函数来返回整个网站的HTML代码。这是我的一个!
public string GetPageContents()
{
string link = "https://www.abc.net.au/news/science/"
string pageContent = "";
WebClient web = new WebClient();
Stream stream;
stream = web.OpenRead(link);
using (StreamReader reader = new StreamReader(stream))
{
pageContent = reader.ReadToEnd();
}
stream.Close();
return pageContents;
}
然后,您可以创建一个返回子字符串或子字符串列表的函数(这意味着,如果需要所有标签,则可能会得到多个)。
List<string> divTags = GetBetweenTags(pageContents, "<div>", "</div>")
这将为您提供一个列表,例如,您可以在每个