【发布时间】:2016-05-16 09:36:37
【问题描述】:
首先请原谅我的英语不好
我想编写一个元搜索引擎
首先,我尝试使用 google bing 和 yahoo api,但它们受到限制
然后我正在尝试使用 htmlagility 包来获取搜索引擎的结果链接
我有这个代码
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 (!hrefValue.ToString().ToUpper().Contains("GOOGLE") && hrefValue.ToString().Contains("/url?q=") && hrefValue.ToString().ToUpper().Contains("HTTP://"))
{
int index = hrefValue.IndexOf("&");
if (index > 0)
{
hrefValue = hrefValue.Substring(0, index);
listBox1.Items.Add(hrefValue.Replace("/url?q=", ""));
}
}
}
}
}
}
我可以将此代码用于所有搜索引擎吗? 我更改了这些行,使其适用于其他搜索引擎
if (!hrefValue.ToString().ToUpper().Contains("YAHOO") && hrefValue.ToString().Contains("/url?q=") && hrefValue.ToString().ToUpper().Contains("HTTP://"))
和
string SearchResults = "http://yahoo.com/search?q=" + textBox1.Text.Trim();
但它不起作用
我的另一个问题是这段代码只返回第一个页面链接。如果我想返回 N 个第一个链接,我该怎么办?
有人可以帮忙吗?
【问题讨论】:
-
您好,欢迎来到 SO。请阅读help center。这个问题目前的格式无法回答。您的问题太宽泛,其中包含多个问题我可以将此代码用于所有搜索引擎,它不起作用,如果我愿意,我应该这样做返回 N 个第一个链接.
-
搜索结果中的所有链接都不是适当的链接,广告链接,谷歌链接也包括在内。我认为你应该改变你的程序逻辑。
标签: c# html-agility-pack meta-search search-engine-api