使用HtmlAgilityPack和c#进行链接提取

时间:2016-05-30 10:08:39

标签: c# html search-engine html-agility-pack

我想提取谷歌结果链接
我的代码工作它确实提取链接,但这些链接不是我期望提取的。 我的程序将提取" a href"标签,但搜索结果中的所有链接都不包括适当的链接,广告链接,谷歌链接 我该怎么办?

using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.Syndication;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace Search
{
public partial class Form1 : Form
{
    // load snippet
    HtmlAgilityPack.HtmlDocument htmlSnippet = new HtmlAgilityPack.HtmlDocument();

    public Form1()
    {
        InitializeComponent();
    }

    private void btn1_Click(object sender, EventArgs e)
    {
        listBox1.Items.Clear();
        StringBuilder sb = new StringBuilder();
        byte[] ResultsBuffer = new byte[8192];
        string SearchResults = "http://google.com/search?q=" + txtKeyWords.Text.Trim();
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SearchResults);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        Stream resStream = response.GetResponseStream();
        string tempString = null;
        int count = 0;
        do
        {
            count = resStream.Read(ResultsBuffer, 0, ResultsBuffer.Length);
            if (count != 0)
            {
                tempString = Encoding.ASCII.GetString(ResultsBuffer, 0, count);
                sb.Append(tempString);
            }
        }

        while (count > 0);
        string sbb = sb.ToString();

        HtmlAgilityPack.HtmlDocument html = new HtmlAgilityPack.HtmlDocument();
        html.OptionOutputAsXml = true;
        html.LoadHtml(sbb);
        HtmlNode doc = html.DocumentNode;

        foreach (HtmlNode link in doc.SelectNodes("//a[@href]"))
        {
            //HtmlAttribute att = link.Attributes["href"];
            string hrefValue = link.GetAttributeValue("href", string.Empty);
     //       if ()
            {
                int index = hrefValue.IndexOf("&");
                if (index > 0)
                {
                    hrefValue = hrefValue.Substring(0, index);
                    listBox1.Items.Add(hrefValue.Replace("/url?q=", ""));
                }
            }
        }
    }
}

}

如果我想和" a href"标签我必须在If中添加一些条件  
但我不知道我应该在这里使用什么条件:

if ()

某个地方我读过关于提取引用标签而不是ahref标签的任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

要获取cite元素中包含的链接,只需访问其内部文本,例如:

    HtmlWeb w = new HtmlWeb();
    var hd = w.Load("http://www.google.com/search?q=veverke");

    var cites = hd.DocumentNode.SelectNodes("//cite");

    foreach (var cite in cites)
        Console.WriteLine(cite.InnerText);