从网页剥离href链接与HtmlAgilityPack

时间:2017-08-17 17:42:01

标签: c# nodes href html-agility-pack

我正在使用HtmlAgilityPack从网站上获取链接。

//part of html from source
string htmlSource="<a class=" ac-algo fz-l ac-21th lh-24" href="http://hoogbegaafdleren.blogspot.com/2011/05/topstudenten-detecteren-in-de.html" target="_blank" data-4fb="5995cb507b349">hoogbegaafdlerenblog: Wat <b>heb</b> je <b>vandaag</b> op school <b>geleerd</b>?</a><a class=" ac-algo fz-l ac-21th lh-24" href="http://gietjes.blogspot.com/2014/09/wat-heb-ik-vandaag-geleerd.html" target="_blank" data-4fb="5995cb507b667">Gietjes Corner: Wat <b>heb</b> <b>ik</b> <b>vandaag</b> <b>geleerd</b>?!</a>"

这是分析html的部分,应该将链接放在列表中

public static List<String> GetLinksFromWebsite(string htmlSource)
{
    var doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml(htmlSource);
    return doc.DocumentNode
            .SelectNodes("......")
            .Select(node => node.Attributes["......"].Value)
            .ToList();
}

我应该填写什么。选择节点和。选择以获取href标签中的URL?

修改

我确实尝试用

选择节点
doc.DocumentNode.SelectNodes("//a[@href]");

但不幸的是,这只返回html中的节点,看起来像

"<a href="http://..................."

但是对于我的代码,我只需要

中的链接
<a class=" ac-algo fz-l ac-21th lh-24" href="http://.........."

这可能吗?

编辑2

要完成:我正在尝试分析搜索结果。所以这就是代码:

    public void Start()
    {
            System.IO.StreamWriter body = new StreamWriter(@"body.txt",     append: true);
            string LookUp="https://search.yahoo.com/search;?p=%27who+is+john+doe%27"
            var htmlSource = client.DownloadString(LookUp);

            foreach (var item in GetLinksFromWebsite(htmlSource))
            {
                 body.WriteLine(item);    
            }

    }


        public static List<String> GetLinksFromWebsite(string htmlSource)
        {
            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(htmlSource);
            return doc.DocumentNode
                    .SelectNodes("......")
                    .Select(node => node.Attributes["......"].Value)
                    .ToList();
        }

其中“p =”标记是要搜索的实际字符串。

这将返回一个包含大量想要和不需要的链接的html。不需要的hrefs是我不需要的yahoo onces。所需的hrefs,它们都是搜索结果,标记为:

<a class=" ac-algo fz-l ac-21th lh-24" href="https://

我只对这些href感兴趣。不幸的是,如果我选择像:

    .SelectNodes("//a[@href]")
    .Select(node => node.Attributes["href"].Value)

我只是得到了不受欢迎的雅虎参考

0 个答案:

没有答案
相关问题