Puppeteer - 如何点击内部元素

Puppeteer - how to click on an inner element

我正在使用 Puppeteer 对使用 React 和 Material-UI 构建的应用程序进行端到端测试。

在我的登录表单中,我试图点击登录按钮,但我得到了 loginBtn.click is not a function - 那是因为 Material UI(版本 0.21.0)正在包装 <RaisedButton> 加上一个额外的 div 所以我只能到达外部元素。我需要一种方法来访问内部元素,然后模拟点击事件。

我试过这个:

const loginBtn = await page.$eval(
    '.login-form-button', 
    (element) => element.innerHTML
);
await loginBtn.click();

但似乎 element.innerHTML 只是一个文本,不可点击。

关于如何获取内部元素的任何想法?

page.$eval selects an element (.login-form-button) and passes that element to the second argument ((element) => element.innerHTML), which will in your case return the HTML of the node as a string. Therefore loginBtn is not a button but a string. To click an element you might want to use page.click.

如果您要执行更复杂的术语,我建议您使用 page.evaluate。在您的情况下,您可以像这样使用它来查询元素并单击它的第一个子元素:

await page.evaluate(() => {
  document.querySelector('.login-form-button').firstElementChild.click();
});