问题
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 &
and '
and more.
example of one result i got from the example code below (again, added spaces between characters intentionally):
title: "Post Malone - "Wow." (Official Music Video)"
Tried solving this by decodeURI ,decodeURIComponent or unescape which didn't help. Used a direct call for youtube api and got the same results. What am i missing?
var youtubeSearch = require("youtube-search")
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);
console.dir(results);
});
回答1:
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 &
回答2:
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);
});
来源:https://stackoverflow.com/questions/55385560/how-to-fix-youtube-api-results-title-that-are-returned-encoded