简体   繁体   中英

How to get only first 15 documents from google news API?

Now my code is returning all the news related to a company. But I want only the first 15 elements. How to do this? Here is the code which returns all the news for a company. google-news-json is a npm package.

export default async function handler(req, res) {
  try {
    let news = await googleNewsAPI.getNews(googleNewsAPI.SEARCH, req.body.companyName, 'en-US')
    res.status(200).json(news)

  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch news' })
  }
}

You need to take a close look at the API reference of google news functionality. There you can find a query parameter ( something like?q=15 or?count=no.of.items ) after your API key to return the count of object that you may want to receive in the fetch url

Typically you'd want to do what @iceweasel suggests in their answer. However, since this package isn't supported by Google (but rather seems to be scraping the HTML produced by directly querying Google News and returning the results as JSON), it doesn't support many of the typical options you'd expect (in particular, limiting the number of returned elements).

If you don't mind the network cost of downloading the full 100 items (which is what your function returns by default), you take the first 15 results from the API's response with:

let top15 = news.items.slice(0, 15)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM