RSSHub/lib/v2/jsu/utils/index.js

53 lines
1.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import got from '@/utils/got'; // 自订的 got
import { load } from 'cheerio'; // 可以使用类似 jQuery 的 API HTML 解析器
/**
* 获取页面内容
* @param selector 正文CSS选择器
* @param pageUrl 页面URL
* @returns {Promise<string|string>} 页面内容为符合RSS规范的HTML
*/
async function getPageItem(selector, pageUrl) {
const response = await got({
method: 'get',
url: pageUrl,
https: { rejectUnauthorized: false },
});
const $ = load(response.data);
const page = $(selector);
return page ? page.html() : '无法获取内容';
}
/**
* 获取页面内容、标题、日期
* @param selector 正文CSS选择器
* @param pageUrl 页面URL
* @param titleSelector 标题CSS选择器
* @param dateSelector 日期CSS选择器
* @param dateHander 日期处理函数在CMS系统中会以“日期点击数”等特殊格式显示日期需要处理切分出日期
* @returns {Promise<{date, pageInfo: string, title: (*|jQuery|string)}|{date: string, pageInfo: string, title: string}>} 页面内容、标题、日期
*/
async function getPageDetails(selector, pageUrl, titleSelector, dateSelector, dateHander = (date) => date) {
const response = await got({
method: 'get',
url: pageUrl,
https: { rejectUnauthorized: false },
});
const $ = load(response.data);
const page = $(selector);
const date = dateHander($(dateSelector).text());
const title = $(titleSelector).text();
return page
? { pageInfo: page.html(), date, title }
: {
pageInfo: '无法获取内容',
date: '1970-1-1',
title: '无法获取标题',
};
}
module.exports = {
getPageItem,
getPageItemAndDate: getPageDetails,
};