How to fix Youtube API results title that are returned encoded

前端 未结 2 1181
萌比男神i
萌比男神i 2021-01-21 11:56

I\'m using youtube-search 1.1.4 to find videos. The problem is that i get the results titles encoded with & or ' instead of just

相关标签:
2条回答
  • 2021-01-21 12:48

    You can use the the DOM Parser

    var parser = new DOMParser;
    
    let finalResult = parser.parseFromString(results, "text/html")
    console.log(finalResult.body.innerHtml); // will turn & to &
    
    0 讨论(0)
  • 2021-01-21 12:54

    After finding a related ticket on google's issue tracker: issuetracker.google.com/u/1/issues/128673539 and got a response from google that this is the expected behaviour and they won't fix it, i just used user 3limin4t0r suggestion and decoded the return value title using he.js library, it's the idle way to solve this but i had no intention to wait for google to come around from their decision...

    so, my solution goes like that:

    var youtubeSearch = require("youtube-search")
    let he            = require('he');
    
    var opts = {
      maxResults  : 15,
      key         : 'MY_API_KEY',
      part        : 'snippet',
      type        : 'video',
    };
    
    youtubeSearch('post malone', opts, function(err, results) {
      if(err) return console.log(err);
      results = results.map(item => {
            item.snippet.title = he.decode(item.snippet.title);
            return item;
       });
      console.dir(results);
    });
    
    0 讨论(0)
提交回复
热议问题