如何使用await page.click、page.waitForSelector等实现函数

问题描述 投票:0回答:1

在主代码中我多次使用这个片段:

(async() => {
(somethning code)

try {
        await page.waitForSelector('.css123', {timeout: 5000});
    } catch (e) {
        console.log(error);
    }
    
    try {
        await page.click('.css123');
    } catch (e) {
        console.log(error);
    }
}

(somethning code)
}

如何在函数中正确声明此代码并在主代码中使用此函数?我尝试了“const save = async() => {}”和“function save() {}” - 它不起作用。

node.js puppeteer
1个回答
0
投票

声明函数有两种方法,您已经提到过它们。

const myFunc = () => {}
function myFunc() {}

// Define the function
const save = async (page) => {
    try {
        await page.waitForSelector('.css123', { timeout: 5000 });
    } catch (error) {
        console.log(error);
    }
    
    try {
        await page.click('.css123');
    } catch (error) {
        console.log(error);
    }
};

// Call the function in your main code
(async () => {
    // (some code)
    
    // Ensure `page` is passed to the `save` function
    await save(page);
    
    // (some other code)
})();
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.