Есть ли рабочий образец rest API пользовательского поиска Google?

Мне нужно создать экран, который автоматизирует поиск в Google. Я знаю JavaScript и пытаюсь заставить GSE работать.

У меня есть поисковая система и ключ API. Проблема в том, что документация Google циклична, то есть страницы указывают друг на друга. Нет рабочего образца, с которого я мог бы начать свое исследование.

Помогите, если знаете рабочий образец.

Я прочитал следующие документы:

  1. cselement-devguide
  2. введение

person Aniruddh Joshi    schedule 06.03.2014    source источник


Ответы (2)


Я знаю, что это старый вопрос, но вот что я сделал, чтобы результаты API были отформатированы так, как раньше давал Google Site Search, поскольку они закрывают платные учетные записи и теперь будут показывать рекламу. У способа API есть возможность оплачивать более 100 поисков в день, так что продолжаем с этим, но все же приходилось форматировать результаты и использовать существующий для создания CSS, чтобы также выполнять аналогичные стили.

Форма поиска для перехода на эту страницу очень проста:

<form action="search-results.htm" id="cse-search-box">
        <div>
            <input class="" name="q" type="text"> 
            <input class="" type="submit">
        </div>
    </form>

а затем страницу результатов поиска:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>JSON/Atom Custom Search API Example</title>
    <!--<link href="default.css" rel="stylesheet" type="text/css">-->
    <link href="google.css" rel="stylesheet" type="text/css">
</head>
<body>
    <div class="gsc-result-info" id="resInfo-0"></div>
    <hr/>
    <div id="googleContent"></div>

<script>
    //Handler for response from google.
    function hndlr(response) {
        if (response.items == null) {
            //Sometimes there is a strange thing with the results where it says there are 34 results/4 pages, but when you click through to 3 then there is only 30, so page 4 is invalid now.
            //So if we get to the invalid one, send them back a page.
            window.location.replace("searchresults.htm?start=" + (start - 10) + "&q=" + query);
            return;
        }
        //Search results load time
        document.getElementById("resInfo-0").innerHTML = "About " + response.searchInformation.formattedTotalResults + " results (" + response.searchInformation.formattedSearchTime + " seconds)";
        //Clear the div first, CMS is inserting a space for some reason.
        document.getElementById("googleContent").innerHTML = "";
        //Loop through each item in search results
        for (var i = 0; i < response.items.length; i++) {
            var item = response.items[i];
            var content = "";

            content += "<div class='gs-webResult gs-result'>" +
                "<table class='gsc-table-result'><tbody><tr>";
            //Thumbnail image
            if (item.pagemap.cse_thumbnail != null)
                content += "<td class='gsc-table-cell-thumbnail gsc-thumbnail'><div class='gs-image-box gs-web-image-box gs-web-image-box-portrait'><a class='gs-image' href='" + item.link + "'>" +
                    "<img class='gs-image' class = 'gs-image-box gs-web-image-box gs-web-image-box-portrait' src='" + item.pagemap.cse_thumbnail[0].src + "'></a></td>";
            //Link
            content += "<td><a class='gs-title' href='" + item.link + "'>" + item.htmlTitle + "</a><br/>";
            //File format for PDF, etc.
            if (item.fileFormat != null)
                content += "<div class='gs-fileFormat'><span class='gs-fileFormat'>File Format: </span><span class='gs-fileFormatType'>" + item.fileFormat + "</span></div>";
            //description text and URL text.
            content += item.htmlSnippet.replace('<br>','') + "<br/><div class='gs-bidi-start-align gs-visibleUrl gs-visibleUrl-long' dir='ltr' style='word-break:break-all;'>" + item.htmlFormattedUrl +"</div>" +
                "<br/></td></tr></tbody></table></div>";
            document.getElementById("googleContent").innerHTML += content;
        }
        //Page Controls
        var totalPages = Math.ceil(response.searchInformation.totalResults / 10);
        console.log(totalPages);
        var currentPage = Math.floor(start / 10 + 1);
        console.log(currentPage);
        var pageControls = "<div class='gsc-results'><div class='gsc-cursor-box gs-bidi-start-align' dir='ltr'><div class='gsc-cursor'>";
        //Page change controls, 10 max.
        for (var x = 1; x <= totalPages && x<=10; x++) {
            pageControls += "<div class='gsc-cursor-page";
            if (x === currentPage)
                pageControls += " gsc-cursor-current-page";
            var pageLinkStart = x * 10 - 9;
            pageControls+="'><a href='search-results.htm?start="+pageLinkStart+"&q="+query+"'>"+x+"</a></div>";
        }
        pageControls += "</div></div></div>";
        document.getElementById("googleContent").innerHTML += pageControls;
    }

    //Get search text from query string.
    var query = document.URL.substr(document.URL.indexOf("q=") + 2);
    var start = document.URL.substr(document.URL.indexOf("start=") + 6, 2);
    if (start === "1&" || document.URL.indexOf("start=") === -1)
        start = 1;

    //Load the script src dynamically to load script with query to call.
    // DOM: Create the script element
    var jsElm = document.createElement("script");
    // set the type attribute
    jsElm.type = "application/javascript";
    // make the script element load file
    jsElm.src = "https://www.googleapis.com/customsearch/v1?key=yourApikeyhere&cx=yoursearchengineidhere&start="+start+"&q=" +query +"&callback=hndlr";
    // finally insert the element to the body element in order to load the script
    document.body.appendChild(jsElm);
</script>
</body>
</html>
person Brent Kilboy    schedule 26.09.2017
comment
Спасибо за пример! На странице результатов URL-адрес страницы часто недействителен из-за наличия пробелов до или после дефиса (-). Вы знаете, что вызывает это? - person riste; 04.03.2020

Место для начала с rest api находится здесь: https://developers.google.com/custom-search/json-api/v1/introduction.

Пример:

<div id="content"></div>
<script>

    // Remember to replace YOUR_API_KEY below.

    function hndlr(response) {
      for (var i = 0; i < response.items.length; i++) {
        var item = response.items[i];
        // in production code, item.htmlTitle should have the HTML entities escaped.
        document.getElementById("content").innerHTML += "<br>" + item.htmlTitle;
      }
    }
</script>
<script src="https://www.googleapis.com/customsearch/v1?key=YOUR_API_KEY&cx=017576662512468239146:omuauf_lfve&q=cars&callback=hndlr">
</script>

Вот скрипка: http://jsfiddle.net/AGjCH/

person Devnook    schedule 06.03.2014
comment
Что такое атрибут cx? Должен ли я изменить его, чтобы он соответствовал моему проекту? - person Aniruddh Joshi; 11.03.2014
comment
Это идентификатор вашего движка, вы можете найти его в Панели управления google.com/cse. - person Devnook; 12.03.2014