javascript - 如何获得与谷歌搜索栏下显示的相同的预测搜索数据
问题描述
我正在尝试找到一种方法来获得与您输入时在 Google 搜索栏下显示的预测搜索结果相同的预测搜索结果。我也不是在谈论对特定站点的自定义搜索。我认为这是不可能的,直到我从 chrome 商店发现了一个新的标签页扩展。
他们的搜索栏预测与谷歌完全匹配。他们从什么来源获取这些数据?是否还有其他任何人都可以推荐的预测搜索服务/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吗?”
我们不能在这里回答这个问题,因为它是题外话。这类问题往往会吸引固执己见的答案和垃圾邮件。
推荐阅读
- html - 输入类型单选垂直对齐
- xml - XML 解析错误 - 需要开始标记,未找到“<”
- python - 在 Jupyter Notebook(Python)的两个轴上是否有图表可以绘制非数字数据(分类数据)?
- rust - 为什么闭包返回类型定义必须包含'_生命周期?
- python - 如何从网站获取文本段落:错误 403 Forbidden
- c# - 轮播图片未加载
- flutter - 渲染 Text() 时在 Widget 中 Flutter If 语句
- arrays - Laravel 从对象中的对象访问值
- scala - 我可以用什么来更好地编写这个 scala 代码?
- android - 如何使用导航组件获取上一个目的地?