微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么我对Google Custom Search API的调用失败并显示请求错误无效参数?

如何解决为什么我对Google Custom Search API的调用失败并显示请求错误无效参数?

我需要获取google搜索的结果才能循环浏览并解析它们。有鉴于此,我(尽我所能)遵循了有关如何进行here

的教程

这是我的代码,基于上面引用的文章中的示例/示例代码

private void btnRentFlick_Click(object sender,EventArgs e)
{
    OpenBestPageForSearchString("rent amazon movie Will Penny");
}

private void OpenBestPageForSearchString(string searchStr)
{
    try
    {
        const string apiKey = "blaBlaBla"; // "blaBlaBla" stands for my API key
        const string searchEngineId = "bla"; // "bla" stands for varIoUs things I tried: my client_id 
            (also called UniqueId),private_key_id (also called KeyId),and project_id. Not having 
             the correct value may be the problem. If so,how do I get it?
        const string query = "rent amazon movie Will Penny"; 
        var customSearchService = new CustomsearchService(new BaseClientService.Initializer { ApiKey 
                                                                                        = apiKey });
        //CseResource.ListRequest listRequest = customSearchService.Cse.List(query); // This is the 
          code in the article,but it won't compile - "no overload for "List" takes one argument"
        // So how is the value in "query" assigned,then?
                
        CseResource.ListRequest listRequest = customSearchService.Cse.List(); 
        listRequest.Cx = searchEngineId;

        List<string> linksReturned = new List<string>();

        IList<Result> paging = new List<Result>();
        var count = 0; // I don't kNow what the purpose of the counting is,but I'll leave as-is 
            until I get it working at least
        while (paging != null)
        {
            listRequest.Start = count * 10 + 1;
            paging = listRequest.Execute().Items; // this takes several seconds,then it throws an       
                                                     exception
            if (paging != null)
            {
                foreach (var item in paging)
                {
                    linksReturned.Add("Title : " + item.Title + Environment.NewLine + "Link : " + 
                        item.Link +
                        Environment.NewLine + Environment.NewLine);
                }    
            }
            count++;
        }
            MessageBox.Show("Done with google amazon query");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }    
    }

如该行末尾的注释所示,此代码行:

paging = listRequest.Execute().Items; 

...工作几秒钟,然后抛出一个异常,即:

enter image description here

那是什么导致此异常?是因为我分配的searchEngineId值不正确吗?还是因为未将搜索字符串(分配给查询变量)提供给调用

有关我的ID的信息包含在google提供的.json文件中,其中没有“ searchEngineId”值。这就是它包含的内容

“类型”:“ service_account”,“ project_id”:“ flix4famsasinlocator”,
“ private_key_id”:“ [我的私钥ID]”,“ private_key”:“ ----- BEGIN 私钥-----。 。 。私钥----- \ n“,” client_email“: “ [bla] .gserviceaccount.com”,“ client_id”:“ [我的客户ID]”,
“ auth_uri”:“ https://accounts.google.com/o/oauth2/auth”,
“ token_uri”:“ https://oauth2.googleapis.com/token”,
“ auth_provider_x509_cert_url”: “ https://www.googleapis.com/oauth2/v1/certs”,
“ client_x509_cert_url”: “ https://www.googleapis.com/robot/v1/Metadata/x509/[bla]gserviceaccount.com”

因此,尽管以前提到的那篇文章据说是,而且乍看起来似乎是医生所命令的,但我碰到了一堵相当大的墙。是否有人知道如何扩展这堵墙-也许主要是通过向CseResource.ListRequest对象提供搜索字符串?

更新

首先尝试使用DalmTo的代码(未显示我逐字复制的他的GetService()方法):

var query = "rent amazon movie Will Penny";

var service = GetService("theRainInSpainFallsMainlyOnTheDirt");

var request = service.Cse.List();

// add option values to the request here.
request.ExactTerms = query;
request.Q = query;

var response = request.ExecuteAsync();
// my contribution:
List<string> linksReturned = new List<string>();

foreach (var item in response.Result.Items)
{
    //Console.WriteLine(item.Title);
    // next two lines also mine
    MessageBox.Show(string.Format("Title: {0}; Link: {1}; ETag: {2}",item.Title,item.Link,item.ETag));
    linksReturned.Add(item.Link);
}

...但是在foreach循环中抛出了此异常:

enter image description here

更新2

是的,这可行(改编自Trekco的答案):

const string apiKey = "gr8GooglyMoogly";
const string searchEngineId = "theRainInSpainFallsMainOnTheDirt"; 
const string query = "rent amazon movie Will Penny";
var customSearchService = new CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey });
CseResource.ListRequest listRequest = customSearchService.Cse.List();
listRequest.Cx = searchEngineId;
listRequest.Q = query;
List<string> linksReturned = new List<string>();

IList<Result> paging = new List<Result>();
var count = 0; 
while (paging != null)
{
    listRequest.Start = count * 10 + 1;
    paging = listRequest.Execute().Items; 
    if (paging != null)
    {
        foreach (var item in paging)
        {
            linksReturned.Add(item.Link);
        }
    }
    count++;
}

解决方法

查询未发送到Google。要修复代码,您需要告诉api使用什么查询。在listRequest.Cx = searchEngineId;之后添加listRequest.Q = query;

var count = 0;
string apiKey = "THE API KEY";
string searchEngineId = "THE SEARCH ENGIN ID";
string query = "rent amazon movie Will Penny";

var customSearchService = new CustomsearchService(new BaseClientService.Initializer
{
    ApiKey = apiKey
});

CseResource.ListRequest listRequest = customSearchService.Cse.List();
listRequest.Cx = searchEngineId;
listRequest.Q = query; // <---- Add this line

List<string> linksReturned = new List<string>();

while (count < 10) // Google limit you to 100 records
{
    listRequest.Start = count * 10;
    var paging = listRequest.Execute().Items; 
    
    foreach (var item in paging)
    {
        linksReturned.Add("Title : " + item.Title + Environment.NewLine + "Link : " +
                          item.Link +
                          Environment.NewLine + Environment.NewLine);
    }

    count++;
}

在您的代码中,您有一个注释,您不知道var count = 0;是什么意思。这是为了跟踪您请求了多少个项目。

如果您查看Google的文档,将会发现它们最多只会返回100个结果。之后,他们会给您一个错误。该错误也将是相同的通用消息:“ INVALID_ARGUMENT”

您可以在此处查看自定义搜索API的要求:https://developers.google.com/custom-search/v1/reference/rest/v1/cse/list

searchEngineId变量是您在网站https://www.google.com/cse/all上生成的搜索引擎ID。您遵循的文档有些过时了。您将在此处找到ID:

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?