4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Googleの力を借りて ”もしかして” する

Last updated at Posted at 2019-03-26

はじめに

誤字った単語から本来の単語を推測したいときがあるかもしれません。
しかしそれを実装するのは大変でしょう。
そんなときは偉大なGoogleの力を借りましょう。

コード

index.html
<html>
<head>
</head>
<body>
  <form id="form">
    <input type="text" id="query" />
    <div id="result"></div>
    <button type="submit">検索</button>
  </form>

  <script type="text/javascript">
    document.getElementById("form").onsubmit = (e) => {
      e.preventDefault();
      (async () => {
        let result = document.getElementById('result');
        let query = document.getElementById("query");
        
        result.innerText = "...";

        let res = await fetch(`https://cors-anywhere.herokuapp.com/www.google.com/search?q=${query.value}`);
        let html = await res.text();
        let parser = new DOMParser();
        let doc = parser.parseFromString(html, "text/html");

        result.innerText = (() => {
          let fprsl = doc.getElementById('fprsl');
          if (fprsl) {
            return "もしかして :" + fprsl.innerText;
          }
          for(let e of doc.getElementsByClassName('gL9Hy')){
            let href = e.getAttribute("href");
            if(href && !href.indexOf("/search?q=")){
              return "もしかして :" + e.innerText;
            }
          }
          return "";
        })();
      })()
    }
  </script>
</body>
</html>

実行してみるとこんな感じ↓

See the Pen ywrmPw by gyojir (@gyojir) on CodePen.

説明

Google検索の"もしかして"機能は2パターンある。
・推測結果で検索までしてくれる
image.png

・推測結果の提案だけする
image.png

それぞれのidとclassのパターンから適当にとってくればよい。

ただCORS制約によりGoogleに直接フェッチすることはできない。
そのためcors-anywhereというサービスを介してフェッチしている。

おしまい

どうせすぐに使えなくなると思う。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?