From 77f1f576435b0e0dd7d55b8df2907fcc17681f31 Mon Sep 17 00:00:00 2001 From: Ethan Shen Date: Mon, 30 Nov 2020 03:00:35 +0800 Subject: [PATCH] fix: pubmed trending articles (#6225) --- lib/routes/pubmed/trending.js | 71 +++++++++++++++++------------------ 1 file changed, 34 insertions(+), 37 deletions(-) diff --git a/lib/routes/pubmed/trending.js b/lib/routes/pubmed/trending.js index 4a1ebd7fb1..e6077c5cdd 100644 --- a/lib/routes/pubmed/trending.js +++ b/lib/routes/pubmed/trending.js @@ -3,61 +3,58 @@ const cheerio = require('cheerio'); const url = require('url'); const date = require('@/utils/date'); -const base = 'https://www.ncbi.nlm.nih.gov'; +const base = 'https://pubmed.ncbi.nlm.nih.gov'; module.exports = async (ctx) => { - const link = `${base}/pubmed/trending/`; + const link = `${base}/trending/`; const response = await got.get(encodeURI(link)); const pageCapture = cheerio.load(response.data); - const list = pageCapture('.content div.rprt > div.rslt').get(); - const out = await Promise.all( - list.map(async (elem) => { + const list = pageCapture('.docsum-content') + .map((_, elem) => { const $ = cheerio.load(elem); - const title = $('p > a').text(); - const partial = $('p > a').attr('href'); - const address = url.resolve(base, partial); - const author = $('div.supp > p.desc').text(); - const pubDate = date($('div.supp > p.details').text().split('. ')[1]); - - const item = { - title, - author, - pubDate, - link: encodeURI(address), + const partial = $('a').attr('href'); + return { + title: $('a').text().trim(), + link: url.resolve(base, partial), + author: $('.full-authors').text(), }; + }) + .get(); - const value = await ctx.cache.get(address); - if (value) { - item.description = value; - } else { - const detail = await got.get(item.link); - const detailCapture = cheerio.load(detail.data); + const out = await Promise.all( + list.map( + async (item) => + await ctx.cache.tryGet(item.link, async () => { + const detail = await got.get(item.link); + const detailCapture = cheerio.load(detail.data); - let authorContents = ''; - if (author !== '') { - authorContents = ` + item.doi = detailCapture('meta[name="citation_doi"]').attr('content'); + item.pubDate = date(detailCapture('meta[name="citation_date"]').attr('content')); + + let authorContents = ''; + if (item.author !== '') { + authorContents = `
- ${author} + ${item.author}
`; - } - const abs = detailCapture('div.abstr > div').html(); - let absContents = ''; - if (abs !== null) { - absContents = ` + } + const abs = detailCapture('#enc-abstract').html(); + let absContents = ''; + if (abs !== null) { + absContents = `

Abstract

${abs}

`; - } - item.description = authorContents + absContents; - ctx.cache.set(address, item.description); - } + } + item.description = authorContents + absContents; - return Promise.resolve(item); - }) + return item; + }) + ) ); ctx.state.data = {