作者:手机用户2502895475 | 来源:互联网 | 2023-06-02 16:45
以前只以为cheerio是nodejs版本的jQuery,可以轻松操作提取HTML,没想到原来还可以操作XML,记录一下。
示例XML: pg132.rdf
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:marcrel="http://id.loc.gov/vocabulary/relators/"
xmlns:dcam="http://purl.org/dc/dcam/"
xmlns:dcterms="http://purl.org/dc/terms/"
xmlns:pgterms="http://www.gutenberg.org/2009/pgterms/"
xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
xmlns:cc="http://web.resource.org/cc/"
>
Public domain in the USA.
Military art and science -- Early works to 1800
text/plain; charset=us-ascii
2013-02-11T14:23:32
130802
application/zip
U
1656
2018-11-01T01:14:54.714978
147635
application/epub+zip
See Project Gutenberg's eBook #17405 for this same text without the translator's annotations, and an HTML version.
See also Wikipedia: 
http://en.wikipedia.org/wiki/The_Art_of_War
application/x-mobipocket-ebook
598683
2018-11-01T01:14:57.358911
Sun Tzu
Sunzi, active 6th century B.C.
孫子
孙子
2018-11-01T01:14:54.344995
text/html
375823
2018-11-01T01:14:56.056948
598690
application/x-mobipocket-ebook
Project Gutenberg
The Art of War
343691
2018-11-01T01:14:54.006974
text/plain
War -- Early works to 1800
1910
application/epub+zip
147634
2018-11-01T01:14:54.597966
en
2013-02-11T14:22:50
343688
text/plain; charset=us-ascii
Text
Giles, Lionel
1958
1875
Sunzi bing fa. English
12393
application/rdf+xml
2018-12-27T04:59:45.761871
1994-05-01
2018-11-01T01:14:54.423973
text/html
375823
Translated from the Chinese by Lionel Giles, M.A. (1910)
Archives containing the RDF files for *all* our books can be downloaded at
http://www.gutenberg.org/wiki/Gutenberg:Feeds#The_Complete_Project_Gutenberg_Catalog
en.wikipedia
zh.wikipedia
en.wikipedia
View Code
index.js
'use strict';
const cheerio = require('cheerio');
const fs = require('fs');
const rdf = fs.readFileSync(`${__dirname}/pg132.rdf`);
const $ = cheerio.load(rdf)
const book = {};
// 找到
的132.(并且转化为int类型)
book.id = +$('pgterms\\:ebook').attr('rdf:about').replace('ebooks/', '')
book.title = $('dcterms\\:title').text()