javascript - Cheerio WebScraping 节点 JS
问题描述
我想抓取一个网页并使用“a”标签内的缩略图或图像(如果存在)获取所有链接。
我能够获取链接,但不确定如何在当前迭代的标签中获取 img > src 值。
const cheerio = require('cheerio')
const request = require('request')
const throttledRequest = require('throttled-request')(request)
throttledRequest.configure({ requests: 18, milliseconds: 1000 })
let o = {
linksOut: []
}
const scrapeLinksOut = (o, body) => {
if (body) {
let $ = cheerio.load(body)
$('a').map(function () {
let link = $(this).attr('href')
// I want to get the img url within the a tag for the current iteration
let thumbnail = $(this).//img > src
o.linksOut.push( {
link: link,
thumbnail: thumbnail
})
})
} else {
// something else
}
}
const scrape = (() => {
return new Promise((resolve, reject) => {
throttledRequest({
url: 'https://www.ibm.com/us-en',
followAllRedirects: true,
timeout: 30000
}, (err, res, body) => {
scrapeLinksOut(o, body)
return resolve(o)
})
})
})
scrape()
.then((res) => {
res.linksOut.forEach((obj) => {
console.log(obj);
})
})
.catch((err) => console.log(err))
解决方案
推荐阅读
- vba - Select 2 rows of data to cut, once cell containing "1" is found
- google-apps-script - How to get a post code & lat/lng coordinates in Google Sheets with an app script?
- javascript - How to break an array value into 2 rows using jsrender
- xcode - 尝试“验证应用程序”或“分发应用程序”时如何访问 Xcode 崩溃日志?
- r - 如何使用 ggplot2 中的 position_fill 将文本与条形图对齐?
- c - 打开mp减少令人困惑
- sql - SQL 触发器更改仅在数据库中进行更改
- r - 如何使用基于其他两个变量的该列的平均值填充原始数据帧子集的给定列中的 NA
- mongodb - MongoDB Schema 验证失败
- python - 在装饰器中通过别名调用函数