我正在尝试通过 C# 在 google 中编写一个简单的搜索,该搜索将运行我选择的查询并检索前 50 个链接。在彻底搜索了类似的工具\正确的 API 之后,我意识到它们中的大多数已经过时了。我的第一次尝试是创建一个“简单的 HttpWebRequest”并扫描接收到的 WebResponse 中的“href=”,结果证明这根本没有回报(冗余)并且非常令人沮丧。我确实有一个 Google API,但我不确定如何将它用于此目的,尽管我知道每天有 1000 个限制。
吉尔
我正在尝试通过 C# 在 google 中编写一个简单的搜索,该搜索将运行我选择的查询并检索前 50 个链接。在彻底搜索了类似的工具\正确的 API 之后,我意识到它们中的大多数已经过时了。我的第一次尝试是创建一个“简单的 HttpWebRequest”并扫描接收到的 WebResponse 中的“href=”,结果证明这根本没有回报(冗余)并且非常令人沮丧。我确实有一个 Google API,但我不确定如何将它用于此目的,尽管我知道每天有 1000 个限制。
吉尔
这是工作代码..显然你必须添加正确的表单和一些简单的控件......
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=", ""));
}
}
}
}
}
}
如果你要走这条路,你应该使用HtmlAgility包进行解析。但是,更好的方法是使用 Google 的 API。看到这篇文章我需要知道我的哪个网址在谷歌上被索引
至于使用HtmlAgility包的一些代码,我的博客上有个帖子 Finding links on a Web page