使用HtmlAgilityPack以正确的格式打印链接

时间:2018-07-10 16:17:35

标签: c# web-scraping format html-agility-pack

我一直在使用HtmlAgilityPack抓取一个网站,但是我需要链接以正确的格式打印出来。在页面上,我正在抓取一些链接,其中包括在链接开头的正确“ https:// ...”格式,但是,大多数链接都以其他方式开头。

例如,一些链接以“ / xxx”开头或仅以“ .//”开头。有什么方法可以对我抓取的链接进行排序,并在其之前打印以正确的“ https://”格式开头的链接?

当前我的代码如下:

var hg = doc.DocumentNode.SelectNodes("//body[@class]");

//Sort through list and print
foreach (var node in hg)
{
foreach(HtmlNode node2 in node.SelectNodes(".//a[@href]")) 
{
    string attributeValue = node2.GetAttributeValue("href", "");
          if (attributeValue[0:7] != "https://")
   {
    Console.WriteLine("https://url/" + node2.Attributes["href"].Value);
   }
}
}
Console.ReadLine();

我一直在尝试使用attributeValue字符串的索引来查看链接的开头,但是不断出现错误消息,告诉我我不能在此处使用索引。也许有更好的方法来检查我不知道的链接的开头?

我是C#的新手,非常感谢您理解此问题!

1 个答案:

答案 0 :(得分:0)

尝试使用StartsWith来尝试索引字符串

var hg = doc.DocumentNode.SelectNodes("//body[@class]");

//Sort through list and print
foreach (var node in hg)
{
  foreach(HtmlNode node2 in node.SelectNodes(".//a[@href]")) 
  {
      string attributeValue = node2.GetAttributeValue("href", "");
            if (!attributeValue.StartsWith("https://"))
     {
      Console.WriteLine("https://url/" + node2.Attributes["href"].Value);
     }
  }
}
Console.ReadLine();