diff --git a/lib/v2/economist/espresso.js b/lib/v2/economist/espresso.js index 6dbdd9c62e..a8b0e3170e 100644 --- a/lib/v2/economist/espresso.js +++ b/lib/v2/economist/espresso.js @@ -15,36 +15,66 @@ module.exports = async (ctx) => { false ); - const gobbets = $('._gobbets ._gobbet p') - .toArray() - .map((item) => { - item = $(item); - return { - title: item.text(), - description: item.html(), - link, - guid: item.text(), - }; - }); + const nextData = JSON.parse($('script#__NEXT_DATA__').text()); + const parts = nextData.props.pageProps.content.hasPart.parts[0].hasPart.parts.filter((part) => part.type.includes('Article')); - const articles = $('._articles ._article') - .toArray() - .map((item) => { - item = $(item); - const title = item.find('h3').text(); - item.find('h3').remove(); - return { - title, - description: item.html(), - link, - guid: item.text(), - }; - }); + const renderHTML = (node) => { + let el; + switch (node.type) { + case 'tag': + el = $(`<${node.name}>`); + for (const name in node.attribs) { + el.attr(name, node.attribs[name]); + } + if (node.children) { + el.append(node.children.map(renderHTML)); + } + return el; + case 'text': + return node.data; + default: + el = $('
'); + el.append(node.map(renderHTML)); + return el; + } + }; + + const gobbetPart = parts.shift(); + const gobbets = gobbetPart.text.map((node, index) => { + const html = renderHTML(node).html(); + return { + guid: `${gobbetPart.id}/${index}`, + link, + title: gobbetPart.headline, + pubDate: gobbetPart.datePublished, + description: html, + }; + }); + + const articles = parts.map((part) => { + const image = part.image.main; + const imgNode = { + type: 'tag', + name: 'img', + attribs: { width: image.width, height: image.height, src: image.url.canonical }, + }; + + const html = renderHTML([imgNode, ...part.text]).html(); + + return { + link, + guid: part.id, + title: part.headline, + pubDate: part.datePublished, + description: html, + }; + }); ctx.state.data = { title: $('head title').text(), link, description: $('meta[property="og:description"]').attr('content'), + language: 'en-gb', item: [...gobbets, ...articles], }; };