首页 > 解决方案 > puppeteer 可以用来自动点击子菜单吗?

问题描述

我正在尝试使用 puppeteer 自动单击子菜单,但这不起作用

var frames = await serv.page.frames();
let lastFrame = frames[frames.length-1];
await lastFrame.waitForNavigation();

await lastFrame.waitForSelector('.reportBuilder-view');
const [more] = await lastFrame.$x("//button[contains(., 'More Actions')]");
await more.click();

console.log(await lastFrame.content());
await serv.wait(1000);
console.log(await lastFrame.content());
console.log('wait for subscribe?')

await lastFrame.waitForSelector('a[title="Subscribe"]');
await lastFrame.click('a[title="Subscribe"]');

我能够逐行模拟单击“更多操作”按钮await more.click();

但是,我无法单击子菜单项。

脚本失败,await lastFrame.waitForSelector('a[title="Subscribe"]');无法选择正确的锚元素。

UnhandledPromiseRejectionWarning: TimeoutError: waiting for selector `a[title="Su
bscribe"]` failed: timeout 30000ms exceeded

我是新手puppeteer,我不明白为什么这段代码不起作用。

也许问题在于子菜单嵌入在具有绝对定位的元素中?

outline: 0px; position: absolute; right: inherit; top: 52px; left: 615px;

也许它是动态添加到 DOM 中的,但为什么它找不到它,因为它已经显示并添加到 DOM 30 秒?

当我查看输出时,lastFrame.content()我可以看到该元素存在于 DOM 中

<li class="slds-dropdown__item actionBarButto
nGroup-action-item report-action-ReportScheduleAction" id="liVM0LRxvZ-item-3" role="presentati
on"><a aria-disabled="false" href="javascript:void(0);" data-index="3" role="menuitem" tabinde
x="-1"><span class="slds-truncate" title="Subscribe">Subscribe</span></a></li>

我在这里做错了吗?

我也尝试等待 XPath,但这也不起作用

await lastFrame.waitForXPath("//li[@class='report-action-ReportScheduleAction']/a");


const [li] = await lastFrame.$x("//li[@class='report-action-ReportScheduleAction']");
console.log('try to click the li');
await li.click();

标签: puppeteerui-automationbrowser-automation

解决方案


实际上标题是跨度而不是锚的属性。

<li class="slds-dropdown__item actionBarButto
    nGroup-action-item report-action-ReportScheduleAction" id="liVM0LRxvZ-item-3" role="presentati
    on">
    <a aria-disabled="false" href="javascript:void(0);" data-index="3" role="menuitem" tabinde
    x="-1">
        <span class="slds-truncate" title="Subscribe">Subscribe</span>
    </a>
</li>

当我单击跨度时,它可以工作

await lastFrame.waitForSelector('span[title="Subscribe"]');
await lastFrame.click('span[title="Subscribe"]');

仍然没有弄清楚为什么li选择器不起作用


推荐阅读