用木偶操作者按下同意按钮

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

我正在使用

"puppeteer": "^19.11.1",
:

我创建了此功能来按此页面上的同意按钮:

这是我的职责:

async function handleConsent(page, logger) {
    const consentButtonSelector =
        '#uc-center-container > div.sc-eBMEME.ixkACg > div > div > div > button.sc-dcJsrY.bSKKNx';


    try {
        // Wait for the iframe to load
        await page.waitForSelector("iframe", { timeout: 3000 });

        // Identify the iframe that contains the consent button
        const iframeElement = await page.$(
            'iframe[name="__tcfapiLocator"]'
        );
        if (iframeElement) {
            const iframeContent = await iframeElement.contentFrame();

            // Attempt to click the consent button within the iframe
            const consentButton = await iframeContent.$(consentButtonSelector);
            if (consentButton) {
                await iframeContent.click(consentButtonSelector);
                logger.info("Consent button clicked inside the iframe.");
            } else {
                logger.info("Consent button not found inside the iframe.");
            }
        } else {
            logger.info("Iframe with the consent message not found.");
        }

        await page.waitForTimeout(3000); // Wait for any potential redirects or updates after clicking
    } catch (error) {
        logger.error(`An error occurred while handling consent: ${error}`);
    }
}

我的问题是找不到选择器,即使我尝试选择 iframe。

对我做错了什么有什么建议吗?

感谢您的回复!

javascript css-selectors puppeteer
1个回答
0
投票

page.waitForSelector("iframe", ...)
只等待 iframe 出现,而不等待其内容加载。使用
page.waitForFrame
代替:

var iframeElement = await page.waitForFrame(async function(frame) {
  return frame.name() === "__tcfapiLocator"
});
(await iframeElement.$(consentButtonSelector))
.evaluate(button => button.click());
© www.soinside.com 2019 - 2024. All rights reserved.