axios 从网站抓取特定文本值

nx7onnlm  于 2022-11-05  发布在  iOS
关注(0)|答案(1)|浏览(134)

这是我在这里的第一个帖子,希望我没有违反任何规则。我试图从https://www.marketwatch.com/economy-politics/calendar中刮取“fed”一词,我可以刮取所有,但我如何才能添加只获取有“fed”一词的数据呢?
这是目前为止的代码。

const PORT = 3000
const express = require('express')
const axios = require('axios')
const cheerio = require('cheerio')

const app = express()

const fedTimes = []

app.get('/', (req,res) => {
    res.json('Welcome to Fed Speech Times')
})

app.get('/fed', (req, res) => {
    axios.get('https://www.marketwatch.com/economy-politics/calendar')
    .then((response) => {
        const html = response.data
        const $ = cheerio.load(html)

        $('td', html).each(function() {
            const title = $(this).text()
                fedTimes.push({
                    title
                })
        })
        res.json(fedTimes)
    }).catch((err) => console.log(err))
})

app.listen(PORT, () => console.log(`server running on PORT ${PORT}`))
h5qlskok

h5qlskok1#

找到了我的答案。下面是代码。tr:contains(speakes)帮我解决了这个问题。

app.get('/stock', (req, res) => {
    axios.get('https://www.marketwatch.com/economy-politics/calendar')
    .then((response) => {
        const html = response.data
        const $ = cheerio.load(html)

        $('tr:contains(speaks)', html).each(function() {
            const time = $(this).text()
                fedTimes.push({
                    time
                })
        })
        res.json(fedTimes)
    }).catch((err) => console.log(err))
})

相关问题