首页 > 解决方案 > 拦截网络选项卡中的特定 URL(无头)并使用 Playwright 和 Nodejs 打开它

问题描述

我想要实现的是使用剧作家的一些自动化:我需要打开一个网页(在我的情况下是路由器 http 服务器),登录到它并监视特定 URL 的网络选项卡。当此 URL 可用时,我需要打开它并将页面打印到日志中。到目前为止,这是我的代码:

const { chromium } = require('playwright');
(async () => {
  const browser = await chromium.launch({ headless: true })
  const context = await browser.newContext()
  const page = await context.newPage()
    
   await page.route('**/ajax/internet.lua', async (route,request) => {
   await page.goto (request.url())});
    
  await page.goto('http://router-ip')
  
  await page.setViewportSize({ width: 1242, height: 568 })
  
  await page.waitForSelector('#login #srp_password')
  await page.click('#login #srp_password')
  await page.keyboard.type('password')
  
  await page.waitForSelector('#login #sign-me-in')
  await page.click('#login #sign-me-in')
  
  await page.waitForNavigation()
  await browser.close()
  
 

})()

使用此代码,我可以成功登录并监视我需要的 URL 的网络日志,但是当我尝试打开它时,我会收到一个无休止的错误循环,直到我强制关闭脚本:

(node:6708) UnhandledPromiseRejectionWarning: page.goto: net::ERR_ABORTED at http://router-ip/ajax/internet.lua
=========================== logs ===========================
navigating to "http://router-ip/ajax/internet.lua", waiting until "load"
============================================================

(node:6708) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6708) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我真的不知道如何修复和继续,所以非常感谢任何帮助,非常感谢。

更新:

最后,这是似乎无需访问 URL 即可工作的代码:这样我将在 console.log 中直接打印页面响应:

page.on('response', async response => {
   if (response.url().includes("/ajax/internet.lua")) {
   resp = await response.json()
   await page.evaluate(() => window.stop())
   console.log(resp)
    }
  })

标签: node.jsplaywright

解决方案


推荐阅读