Youtube API 搜索自动完成



我正在使用Youtube API,我希望有一个搜索自动完成功能,就像在YouTube上一样,当您在搜索输入框中输入时,它会为您提供搜索建议。我已经阅读了文档,但仍然缺少,使用 API 可以吗?

好的,

我找到了这个网址:

http://suggestqueries.google.com/complete/search?client=firefox&ds=yt&q=Query

它不是Youtube API的一部分,但仍然可以工作,返回JSON响应。

对于 json,只需添加"client"参数:

http://suggestqueries.google.com/complete/search?client=youtube&ds=yt&client=firefox&q=Query

最重要的是,API

旧的,并且提供谷歌搜索建议而不是YouTube搜索建议

使用这个:

https://clients1.google.com/complete/search?client=youtube&gs_ri=youtube&ds=yt&q=faded

使用以下 JS 代码提取建议:

//  data is response of above api
   const data = 'window.google.ac.h(["faded",[["faded",0,[433]],["faded alan walker lyrics",0,[433]],["faded remix",0,[433]],["faded 8d",0,[433]],["faded piano",0,[433]],["faded wheel free fire",0],["faded karaoke",0,[433]],["faded ringtone",0,[433]],["faded instrumental",0,[433]],["faded live",0,[433]],["faded piano tutorial",0,[433]],["faded whatsapp status",0,[433]],["faded dhol cover",0,[433]],["faded dance",0,[433]]],{"k":1,"q":"_sPyvXmmbfcsVtfP4sgjOdKQAvg"}])';
    const searchSuggestions = [];
    data.split('[').forEach((ele, index) => {
      if (!ele.split('"')[1] || index === 1) return;
        return searchSuggestions.push(ele.split('"')[1]);
    });
    console.log(searchSuggestions);

查看 YouTube 自动完成关键字抓取器 .不太确定提出问题的人想要YouTube自动完整解决方案的背景,但我想我会把它扔在那里。

你也可以使用 JSON:

url: "https://suggestqueries.google.com/complete/search?client=youtube&ds=yt&q=" + i,
        dataType: "jsonp",

官方的:

https://suggestqueries-clients6.youtube.com/complete/search?client=youtube-reduced&hl=en&gs_ri=youtube-reduced&ds=yt&cp=3&gs_id=100&q=Nectar&xhr=t&xssi=t&gl=us

您也可以选择国家/地区。

附言我在美国国家搜索了花蜜

发出获取请求后

const res = await fetch(
    `https://clients1.google.com/complete/search?client=youtube&gs_ri=youtube&ds=yt&q=${searchTerm}`,
  );
const str = await res.text();
// const str = window.google.ac.h(["faded",[["faded",0,[433]],["faded alan walker lyrics",0,[433]],["faded remix",0,[433]],["faded 8d",0,[433]],["faded piano",0,[433]],["faded wheel free fire",0],["faded karaoke",0,[433]],["faded ringtone",0,[433]],["faded instrumental",0,[433]],["faded live",0,[433]],["faded piano tutorial",0,[433]],["faded whatsapp status",0,[433]],["faded dhol cover",0,[433]],["faded dance",0,[433]]],{"k":1,"q":"_sPyvXmmbfcsVtfP4sgjOdKQAvg"}])'

您可以通过首先剪切不必要的部分来直接解析响应

const arr = JSON.parse(str.substring(str.indexOf("["), str.indexOf("])") + 1));

这是结果的形状

let suggestionsTuple: [string, number, number[]][] = [];

我们所需要的只是过滤掉string

if (Array.isArray(arr) && Array.isArray(arr.at(1))) {
    suggestionsTuple = arr.at(1);
}
const suggestions = suggestionsTuple.flatMap((suggestion) => suggestion).filter((suggestion) => typeof suggestion === "string"); // ["faded" ,"faded alan walker lyrics", ...]

相关内容

  • 没有找到相关文章

最新更新