You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Node.js应用中通过google-trends npm包获取Google Trends热门榜单?

Hey there! I’ve faced similar frustrations with the google-trends npm package’s limited methods when trying to pull annual top actor/movie data for specific countries. Here are a few actionable workarounds I’ve used successfully:

The package doesn’t have a direct "annual top list" method, but you can chain its existing functions to build the data yourself:

  • Step 1: Use autoComplete to get a relevant seed term (like "actors" or "movies") tailored to your target country.
  • Step 2: Fetch top related topics with relatedTopics, filtering for entries tagged as "Actor" or "Movie".
  • Step 3: For each topic, pull monthly search data with interestOverTime for your target year.
  • Step 4: Aggregate monthly values to get total annual interest, then sort to find the highest-ranked entries.

Here’s a code example for top actors:

const googleTrends = require('google-trends-api');

async function getTopAnnualActors(countryCode, targetYear) {
  // Get a country-specific seed term
  const autoCompleteResult = await googleTrends.autoComplete({
    keyword: 'actors',
    geo: countryCode
  });
  const seedTerm = autoCompleteResult.default[0].value;

  // Fetch all actor-related topics for the year
  const relatedTopicsResult = await googleTrends.relatedTopics({
    keyword: seedTerm,
    geo: countryCode,
    time: `${targetYear}-01-01 ${targetYear}-12-31`
  });

  // Filter to only include actor entries
  const actorTopics = relatedTopicsResult.default.rankedList[0].rankedKeyword
    .filter(item => item.topic.type === 'Actor');

  // Calculate total annual search interest for each actor
  const annualInterestData = await Promise.all(actorTopics.map(async (actor) => {
    const interestData = await googleTrends.interestOverTime({
      keyword: actor.topic.title,
      geo: countryCode,
      time: `${targetYear}-01-01 ${targetYear}-12-31`
    });
    const monthlyValues = interestData.default.timelineData.map(entry => parseInt(entry.value[0]));
    const totalAnnualInterest = monthlyValues.reduce((sum, val) => sum + val, 0);
    return { name: actor.topic.title, totalInterest: totalAnnualInterest };
  }));

  // Sort actors by highest annual interest
  return annualInterestData.sort((a, b) => b.totalInterest - a.totalInterest);
}

// Test with US, 2023
getTopAnnualActors('US', 2023)
  .then(topActors => console.log('Top 2023 US Actors:', topActors))
  .catch(err => console.error('Error fetching data:', err));

The google-trends package doesn’t expose Google’s internal year-end top list endpoints, but you can call them directly with node-fetch (or similar tools). These endpoints return pre-computed annual rankings, which saves you from aggregating data manually.

Here’s an example for top movies:

const fetch = require('node-fetch');

async function getTopAnnualMovies(countryCode, targetYear) {
  // Category 11 = Movies; adjust category ID for actors (you'll need to find the right ID)
  const apiUrl = `https://trends.google.com/trends/api/topcharts/${targetYear}?hl=en-US&tz=360&geo=${countryCode}&category=11`;
  
  const response = await fetch(apiUrl, {
    headers: {
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
    }
  });

  // Google adds a 4-character prefix to the JSON response; strip it before parsing
  const rawResponse = await response.text();
  const parsedData = JSON.parse(rawResponse.slice(4));

  // Extract movie names and their trend URLs
  return parsedData.topCharts.map(item => ({
    name: item.title,
    trendUrl: `https://trends.google.com${item.exploreUrl}`
  }));
}

// Test with UK, 2023
getTopAnnualMovies('GB', 2023)
  .then(topMovies => console.log('Top 2023 UK Movies:', topMovies))
  .catch(err => console.error('Error fetching top movies:', err));

Note: Google may modify these endpoints or block requests without proper headers, so you’ll need to test regularly. Also, ensure you comply with Google’s Terms of Service.

3. Fallback to Third-Party Aggregators

If the above methods feel too fragile, consider using third-party APIs that aggregate Google Trends annual data. These services often provide structured, country-specific rankings for actors and movies, though you may need to sign up for an API key.

内容的提问来源于stack exchange,提问作者Mrutyunjaya Jena

火山引擎 最新活动