首页 > 解决方案 > 如何获得与谷歌搜索栏下显示的相同的预测搜索数据

问题描述

我正在尝试找到一种方法来获得与您输入时在 Google 搜索栏下显示的预测搜索结果相同的预测搜索结果。我也不是在谈论对特定站点的自定义搜索。我认为这是不可能的,直到我从 chrome 商店发现了一个新的标签页扩展。

https://chrome.google.com/webstore/detail/start-a-better-new-tab/kgifkabikplflflabkllnpidlbjjpgbp?hl=en

他们的搜索栏预测与谷歌完全匹配。他们从什么来源获取这些数据?是否还有其他任何人都可以推荐的预测搜索服务/API?

标签: javascriptsearchsearchbargoogle-search-api

解决方案


“他们从什么来源获取数据?”

通过查看扩展的源代码,这个 URL:
https ://google.com/complete/search?client=firefox&hl=en&q=foo

它与 Google 在其搜索页面上使用的 API 相同。但该 API 受CORS 政策保护,因此无法从任何网页访问。浏览器扩展可以,因为它被授予了更多权限。要使用它,您需要一个代理服务器(您自己的或免费的,例如下面示例中的那个)。

const searchInput = document.getElementById('search'),
  suggestionsList = document.getElementById('suggestions');

searchInput.addEventListener('input', autocomplete);
autocomplete();

function autocomplete() {
  const q = searchInput.value;
  const proxy = 'https://cors-everywhere.herokuapp.com/';
  
  fetch(`${proxy}https://google.com/complete/search?client=firefox&hl=en&q=${q}`, {
    headers: { origin: 'google.com' }
  })
  .then(res => res.json())
  .then(res => {
    suggestionsList.innerHTML = res[1].map(x => `<li>${x}</li>`).join('')
  });
}
<input id="search" value="foo" />
<ul id="suggestions"></ul>

“还有其他……服务/API吗?”

我们不能在这里回答这个问题,因为它是题外话。这类问题往往会吸引固执己见的答案和垃圾邮件。


推荐阅读