【问题标题】:Getting the number of google search hits with google api使用 google api 获取 google 搜索点击次数
【发布时间】:2017-10-27 04:28:42
【问题描述】:

我正在尝试使用自定义搜索引擎获取搜索结果的数量。我尝试了以下代码:

    String charset = "UTF-8";
    String google = "https://www.googleapis.com/customsearch/v1?key={mykey}" +
                "&cx={mycxcode}&q=" +URLEncoder.encode(searchString, charset) +
                ")&fields=queries(request(totalResults)";
    String userAgent = "Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
    String totalResultsElementText = Jsoup.connect(google).userAgent(userAgent).ignoreContentType(true).get().text();

对于此代码,我收到以下错误消息: org.jsoup.HttpStatusException:获取 URL 的 HTTP 错误。状态=400,网址={myurl}

我做错了什么?

【问题讨论】:

    标签: api jsoup google-crawlers


    【解决方案1】:

    您创建的网址有错误。您应该将参数 fields 更改为

    &fields=queries/request(totalResults),因为requestqueries 的字段,而不是数组。

    更多关于部分选择器的信息可以在here找到。

    String charset = "UTF-8";
    String google = "https://www.googleapis.com/customsearch/v1?key={mykey}" +
                    "&cx={mycxcode}&q=" +URLEncoder.encode(searchString, charset) +
                    "&fields=queries/request(totalResults)";
    String userAgent = "Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)";
    String totalResultsElementText = Jsoup.connect(google).userAgent(userAgent).ignoreContentType(true).get().text();
    

    您的结果采用 JSON 格式,因此您可以像这样提取最终值:

    JSONObject json = new JSONObject(totalResultsElementText);
            System.out.println(json.getJSONObject("queries").getJSONArray("request").getJSONObject(0).get("totalResults"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 2016-05-09
      • 1970-01-01
      相关资源
      最近更新 更多