puppeteer 浏览器在某个 URL 或者网页上有某个元素是否可以触发事件?

Is it possible to trigger an event if a puppeteer browser is on a certain URL or has a certain element on the webpage?

如果浏览器在某个URL或者网页上有某个元素,是否可以通过puppeteer触发事件?

我打开了一个浏览器,用户与页面交互并做任何他们想做的事,直到他们到达某个 URL。是否可以触发这样的事件?

是的,这是可能的。您描述的两个选项都是可行的。更简单的方法是检查正在发生的请求。

检查 requests/URLs

这是一个代码示例,它通过在 request event. Keep in mind that the request could be happening anywhere on the page (in an iframe for example). Depending on your use case, you might therefore also want to check if the request happened inside the main page (by using page.url()) 上列出来检查正在发生的请求。

page.on('request', request => {
  const url = request.url();
  if (url === '...') {
     // trigger event
  }
});

检查元素

如果要检查页面上是否存在特定元素,可以等待 domcontentloaded 事件,然后检查元素是否存在:

page.on('domcontentloaded', () => {
  const element = page.$('#element-selector');
  if (element) {
    // element is present, trigger event
  }
});

请记住,这只会检查一次。要连续检查元素是否存在,您可以使用 MutationObserver (see an example for that ).