【问题标题】:Finding a div content based on attribute value根据属性值查找div内容
【发布时间】:2019-10-28 08:41:56
【问题描述】:

Node-red 节点,用于与旧的通风系统集成,使用屏幕抓取,nodejs 和cheerio。现在可以很好地获取一些值,但我似乎无法在更复杂的结构化中获取正确的元素,告诉哪个操作模式处于活动状态。附结构截图。是的,从来没有用过 jquery,而且是个 Cheerio 上的新手。

如果它在树的某个部分内,我已经设法获得值,方法很复杂。

const msgResult = scraped('.control-1');
const activeMode = msgResult.get(0).children.find(x => x.attribs['data-selected'] === '1').attribs['id'];

但仅适用于第一次匹配,如果数据选择 === 1 不在树的该部分中,则失败。以为我应该能够从树的顶部使用 .find ,但没有匹配项。

const activeMode = scraped('.control-1').find(x => x.attribs['data-selected'] === '1')

我想从附加的 html 结构中得到的是具有 data-selected=1 的 div 的 ID,它也可以位于 control-1 类的两个 div 中的任何一个之下。也可能是底层跨度的内容,模式在文本中描述。

HTML structure

【问题讨论】:

    标签: node.js cheerio


    【解决方案1】:

    很难说你在找什么,但也许:

    $('.control-1 [data-selected="1"]').attr('id')
    

    【讨论】:

    • 是的,它有点工作,但出于某种原因,只有在具有 class=control-1 的第二个 div 上的“data-selected=1”时。根据通风控制器上激活的模式 (div) 移动数据选择的服装。 ``` const activeMode = scraped('[data-selected="1"]').attr('id'); ``` 会找到它,但只能在第二个 div control1 上找到。
    • 抱歉,我不太明白。
    • 好的,我会再试一次。在附图中,显示了 html 结构 - controlh-1 类的一个 div,包含 control-1 类的子 div - 这两个 control-1 div 都包含通风的不同操作模式的 div,由它们的 id 给出,即 om1、oc-1 等。哪个是活动的由 data-selected=1 显示 - 如果 data-selected=1 位于类 control-1 的第二个 div 中,我似乎只能通过 find 得到答案
    【解决方案2】:

    你应该尝试做一些循环来检查每棵树。

    试试这个代码,希望它有效。

    const cheerio = require ('cheerio')
    const fsextra = require ('fs-extra');
    
    (async () => {
        try {
    
            const parseFile = async (error, contentHTML) => {
    
                let $ = await cheerio.load (contentHTML)
                const selector = $('.control-1 [data-selected="1"]')
    
                for (let num = 0; num < selector.length; num++){
                    console.log ( selector[num].attribs.id )
                }
            }
    
            let activeMode = await fsextra.readFile('untitled.html', 'utf-8', parseFile )
    
        } catch (error) {
            console.log ('ERROR: ', error)
        }
    })()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      • 1970-01-01
      • 2012-09-02
      • 1970-01-01
      • 2023-03-29
      • 2012-09-27
      相关资源
      最近更新 更多