gpt4 book ai didi

node.js - 如何在 Node.js 中从 xml 中抓取 url?

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:50 25 4
gpt4 key购买 nike

我的最终目标是让我的应用程序显示来自给定用户的 500px.com 帐户(这是一个摄影网站)的 X 张最新图像的缩略图。据我所知,该网站没有 API,但它确实为个人用户提供了 rss feed,即 https://500px.com/janedoe/rss ,输出 xml。

使用 xml2js,我可以将 xml 解析为 js 对象,并导航到“描述”容器,其中包含包含我想要的 url 的 html,如下所示(这只是使用 rss feed 中第一项的概念证明):

var express = require('express');
var router = express.Router();
var request = require('request');
var parseString = require('xml2js').parseString;

var EventEmitter = require('events').EventEmitter;
var body = new EventEmitter();

/* GET home page. */
router.get('/', function(req, res, next) {


request("https://500px.com/janedoe/rss", function(error, response, data) {
body.data = data;
body.emit('update');
});

body.on('update', function() {
parseString(body.data, function (err, result) {
var photoLink = result.rss.channel[0].item[0].description[0];
res.render('index', { title: 'Express', photoName});
});
});



});

这会将“!CDATA”标记的整个 html 内容放入 photoLink 变量中。我想要做的是定位该 html 中 img src 中的内容,以便我可以将 url 作为要在页面上呈现的字符串传递。

我可以设想使用字符串方法来查找第一个“img src”标签,然后读入直到地址末尾,但是有没有更优雅和简单的方法来做到这一点?

最佳答案

试试这个:在这个例子中,我找到了所有的图像网址

const transform = require('camaro')
const cheerio = require('cheerio')

const xml = require('fs').readFileSync('feed.xml', 'utf-8')

const template = {
data: ['//item/description', '.']
}

const result = transform(xml, template)

const links = result.data.map(html => {
const $ = cheerio.load(html)
const links = $('img')
const urls = []
$(links).each(function(i, link) {
urls.push($(link).attr('src'))
})
return urls
})

console.log(links)

输出:

[ [ 'https://drscdn.500px.org/photo/629350/m%3D900/v2?webp=true&sig=4a9fa5788049efb196917cc3f1a55601af901c7157b59ec86c8aa3378c6ee557' ],
[ 'https://drscdn.500px.org/photo/625259/m%3D900/v2?webp=true&sig=55eab44535f05625ad25dae3e805b2559c1caeb4c97570d04ee0a77c52c7fb19' ],
[ 'https://drscdn.500px.org/photo/625253/m%3D900/v2?webp=true&sig=174d1b27e6f87e0a98192cf6ae051301681a51beb7297df9733956d2763af163' ],
[ 'https://drscdn.500px.org/photo/509064/m%3D900/v2?webp=true&sig=698e56114e1d8b67ad11823390f8456ae723d3a389191c43192718f18213caa8' ],
[ 'https://drscdn.500px.org/photo/509061/m%3D900/v2?webp=true&sig=2998212f82a1c3428cebb873830a99b908f463474045d4e5ebba3257808685dd' ],
[ 'https://drscdn.500px.org/photo/509060/m%3D900/v2?webp=true&sig=8082904fe1935c51fc301a0d10529475ee15124d3797f69cbaeac3fd6c5f0dcb' ],
[ 'https://drscdn.500px.org/photo/509056/m%3D900/v2?webp=true&sig=4b85086a7bf55709e77febb202636b0e09415c8ca3fc3657bfb889ad827b3cab' ] ]

关于node.js - 如何在 Node.js 中从 xml 中抓取 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45605487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com