首页 > 解决方案 > Puppeteer - 最佳标准实践

问题描述

在 puppeteer 上进行常见操作的最佳(或标准)方法是什么?

考虑一下:

<div class="C1">
    <img alt="Bla Bla" class="C2" scrset="lots of stuff here" scr="THIS_IS_WHAT_I_WANT">

我想访问 src 文本。最好的方法是什么?

或者我在网页上有这个的另一种情况:

<a class="D1 D2 D3" role="button" </a>

我想检查像上面按钮这样的元素的存在(和不存在)。

标签: node.jspuppeteer

解决方案


您的第一个示例(获取 src 文本):

const puppeteer = require('puppeteer')

async function run() {
    const browser = await puppeteer.launch()
    const page = await browser.newPage()

    await page.goto(`insertYourURLhere.com`, {
        timeout: 0,
        waitUntil: ['domcontentloaded']
    })
    
    // getting a handle on the div first
    const outerDiv = await page.$('div.C1')
    // proceeding from the selected div
    const scrAttribut = await outerDiv.$eval('img.C2', el => el.getAttribute('scr'))

    console.log(scrAttribut)
    
    browser.close()
}

run()

您的第二个示例(检查元素的存在):

您使用与上面所示相同的方法来查找外部 div 按钮:

page.$(selector)

然后检查返回值。

如果没有元素匹配选择器,则返回值解析为null。

来自:Puppeteer 文档


推荐阅读