【发布时间】:2016-06-08 17:07:38
【问题描述】:
这是我的过程:
我有一个textbox,用户会在其中输入关键字,例如games,然后输入后所有与游戏相关的网站都会以windows形式输出。
基本上我尝试使用 Google Search API,使用以下代码:
const string apiKey = "";
const string searchEngineId = "";
const string query = "games";
CustomsearchService customSearchService = new CustomsearchService(new Google.Apis.Services.BaseClientService.Initializer() { ApiKey = apiKey });
Google.Apis.Customsearch.v1.CseResource.ListRequest listRequest = customSearchService.Cse.List(query);
listRequest.Cx = searchEngineId;
Search search = listRequest.Execute();
foreach (var item in search.Items)
{
Console.WriteLine("Title : " + item.Title + Environment.NewLine + "Link : " + item.Link + Environment.NewLine + Environment.NewLine);
}
但我的问题是 100 个查询/天和 10 个结果/查询的限制不适用。
所以我决定使用 HttpWebRequest 和 HttpWebResponse 的方法, 这是我从网上看到的代码:
StringBuilder sb = new StringBuilder();
// used on each read operation
byte[] buf = new byte[8192];
string GS = "http://google.com/search?q=sample";
// prepare the web page we will be asking for
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GS);
// execute the request
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Encoding.ASCII.GetString(buf, 0, count);
// continue building the string
sb.Append(tempString);
}
}
while (count > 0);
我的问题是它返回整个 HTML,是否可以像使用 Google Search API 一样只获取 URL
【问题讨论】: