如何获取与 Windows 窗体 C# 中的关键字相关的所有网站



这是我的过程:我有一个textbox,用户将在其中输入关键字,例如游戏,然后在输入后,与游戏相关的所有网站都将输出到Windows表单中。

基本上,我尝试使用以下代码使用Google搜索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

这就是它的工作方式,你要么必须为 API 付费,要么解析 HTML - 后者的合法性值得怀疑。

使用带有 css 选择器的 html 解析器,它不需要那么多工作(解决方案基于这个 java 教程:http://mph-web.de/web-scraping-with-java-top-10-google-search-results/)。我使用了 Dcsoup(https://github.com/matarillo/dcsoup 不完整的 Jsoup 移植)作为示例,因为我习惯了 Jsoup(https://jsoup.org/apidocs/),但可能还有其他用于 c# 的 html 解析器维护得更好,等等。

// query results on page 14, to demonstrate that limit of results is avoided
int resultPage = 130;
string keyword = "test";
string searchUrl = "http://www.google.com/search?q="+keyword+"&start="+resultPage;
System.Net.WebClient webClient = new System.Net.WebClient();
string htmlResult = webClient.DownloadString(searchUrl);
Supremes.Nodes.Document doc = Supremes.Dcsoup.Parse(htmlResult, "http://www.google.com/");
// parse with css selector
foreach (Supremes.Nodes.Element result in doc.Select("h3.r a")) 
{
    string title = result.Text;
    string url = result.Attr("href");
    // do something useful with the search result
    System.Diagnostics.Debug.WriteLine(title + " -> " + url);
}

所需的选择器h3.r a可能会更改。更稳定的替代方法可能是解析所有元素并检索具有href属性的元素,或者至少具有内置检查(检查具有大量结果的搜索词并解析,如果您的选择器没有结果,请向您发送通知以修复选择器)。

另请参阅有关获取确切搜索词结果的答案:https://stackoverflow.com/a/37268746/1661938

最新更新