fix(route): AP News (#7035)

This commit is contained in:
mjysci
2021-03-02 01:58:09 -05:00
committed by GitHub
parent cd4c872161
commit d2abeb9883
3 changed files with 37 additions and 54 deletions
+32 -51
View File
@@ -1,62 +1,43 @@
const got = require('@/utils/got');
const cheerio = require('cheerio');
const url = require('url');
const HOME_PAGE = 'https://apnews.com';
module.exports = async (ctx) => {
const topic = ctx.params.topic;
const response = await got({
method: 'get',
url: `https://apnews.com/${topic}`,
});
const browser = await require('@/utils/puppeteer')();
const page = await browser.newPage();
const url_link = `${HOME_PAGE}/hub/${topic}`;
await page.goto(url_link);
const html = await page.evaluate(() => document.documentElement.innerHTML);
browser.close();
const data = response.data;
const $ = cheerio.load(html);
const $ = cheerio.load(data);
// const list = $('div.FeedCard');
const list = [];
$('div.FeedCard').each(function (index, item) {
if ($(item).find('a[class^=Component-headline]').attr('href') !== undefined) {
list.push(item);
}
});
const out = await Promise.all(
list.map(async (article) => {
const link = url.resolve('https://apnews.com', $(article).find('a[class^=Component-headline]').attr('href'));
const [title, author, pubDate, description] = await ctx.cache.tryGet(link, async () => {
const result = await got.get(link);
const $ = cheerio.load(result.data);
const head = JSON.parse($('script[type="application/ld+json"]').html());
const title = head.headline;
const author = head.author.join(' & ');
const pubDate = head.datePublished;
const text = $('div.Article').html();
const imageUrl = head.image;
const description = `<img src="${imageUrl}">` + text;
return [title, author, pubDate, description];
});
const item = {
title: title,
description: description,
pubDate: pubDate,
link: link,
author: author,
};
return Promise.resolve(item);
})
);
const list = $('div.FeedCard');
ctx.state.data = {
title: 'AP News - ' + $('title').text(),
link: `https://www.apnews.com/${topic}`,
item: out,
title: $('.Body div').find('h1[class^=hubTitle]').text(),
link: HOME_PAGE,
item: list
.slice(0, 5)
.map((index, item) => {
item = $(item);
const title = item.find('h1[class^=Component-h1]').text();
const link = item.find('a[class^=Component-headline-]').attr('href');
const pubDate = item.find('span[class^=Timestamp]').attr('title');
const text = item.find('div[class^=content]').text();
const imageUrl = item.find('img[class^=image-]').attr('src');
const author = item.find('span[class^=Component-bylines-]').text().slice(3);
return {
title: title,
description: `<img src="${imageUrl}">` + text,
link: `${HOME_PAGE}${link}`,
pubDate: pubDate,
author: author,
};
})
.get(),
};
};