From ec39bfb29bec02bca922897bafd5317cc32dff00 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=8F=E6=A1=90=E6=A1=90?= <32215330+arbent@users.noreply.github.com> Date: Tue, 4 Sep 2018 22:52:17 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8DJSON=E9=87=8D=E5=A4=8Dparse?= =?UTF-8?q?=E7=AD=89=E9=97=AE=E9=A2=98=20(#641)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- routes/xkcd/comic.js | 20 +++++++------------- routes/xkcd/what-if.js | 31 +++++++++++++++++++------------ 2 files changed, 26 insertions(+), 25 deletions(-) diff --git a/routes/xkcd/comic.js b/routes/xkcd/comic.js index 139872c2f2..634c67cc37 100644 --- a/routes/xkcd/comic.js +++ b/routes/xkcd/comic.js @@ -1,17 +1,11 @@ const axios = require('../../utils/axios'); module.exports = async (ctx) => { - const response = await axios({ - method: 'get', - url: 'https://xkcd.com/info.0.json', - headers: { - Referer: 'https://www.xkcd.com', - }, - }); + const response = await axios.get('https://xkcd.com/info.0.json'); - const data = JSON.parse(response.data); + const result = response.data; const postTime = new Date(); - postTime.setFullYear(parseInt(data.year), parseInt(data.month) - 1, parseInt(data.day)); + postTime.setFullYear(parseInt(result.year), parseInt(result.month) - 1, parseInt(result.day)); postTime.setHours(0, 0, 0, 0); // 无法获取精确时间 ctx.state.data = { @@ -20,11 +14,11 @@ module.exports = async (ctx) => { description: 'A webcomic of romance, sarcasm, math, and language.', item: [ { - title: data.title, - description: `
${data.alt}`, + title: result.title, + description: `
${result.alt}`, pubDate: postTime.toUTCString(), - link: 'https://www.xkcd.com/' + data.num, - guid: data.num, + link: 'https://www.xkcd.com/' + result.num, + guid: result.num, }, ], }; diff --git a/routes/xkcd/what-if.js b/routes/xkcd/what-if.js index cc8a0c95f7..d40a4c82fb 100644 --- a/routes/xkcd/what-if.js +++ b/routes/xkcd/what-if.js @@ -4,27 +4,34 @@ const cheerio = require('cheerio'); module.exports = async (ctx) => { const response = await axios({ method: 'get', - url: 'https://what-if.xkcd.com/', + url: 'https://what-if.xkcd.com/feed.atom', headers: { - Referer: 'https://what-if.xkcd.com/', + Referer: 'https://xkcd.com/', }, }); const data = response.data; - const $ = cheerio.load(data); + const $ = cheerio.load(data, { + xmlMode: true, + }); + const list = $('entry'); ctx.state.data = { title: 'what-if', link: 'https://what-if.xkcd.com/', description: "xkcd' article", - item: [ - { - title: $('h1').text(), - description: $('#question').text(), - pubDate: '', // 发表日期无法获取 - guid: '', - link: 'https:' + $('article a:first').attr('href'), - }, - ], + item: + list && + list + .map((index, item) => { + item = $(item); + return { + title: item.find('title').text(), + description: item.find('content').text(), + pubDate: item.find('updated').text(), + link: item.find('id').text(), + }; + }) + .get(), }; };