Saltar al contenido
Last updated

Automatización de Puppeteer en Node.js

Este es un ejemplo completo y ejecutable de Node.js que demuestra cómo iniciar un perfil MoreLogin a través de la API local y conectarse a él usando Puppeteer.

Nota: Esto requiere que el cliente MoreLogin esté ejecutándose y que haya iniciado sesión localmente.

Requisitos previos

npm install puppeteer axios

Guión de ejemplo

const puppeteer = require("puppeteer");
const axios = require("axios");

// Start a browser profile and return the debug port
async function getDebugPort(profileId) {
  const url = `http://localhost:40000/api/env/start`;
  
  try {
    const response = await axios.post(url, { envId: profileId });
    if (response.data.code === 0) {
      return response.data.data.debugPort;
    } else {
      console.error(`API Error: ${response.data.msg}`);
      return -1;
    }
  } catch (error) {
    console.error(`Request Failed: ${error.message}`);
    return -1;
  }
}

(async function run() {
  // Replace with your actual profile ID
  const profileId = "1907751741233373184"; 
  
  const port = await getDebugPort(profileId);
  if (port <= 0) {
    console.log("Failed to start the environment");
    return;
  }

  console.log(`Connected to port: ${port}`);
  
  // Connect Puppeteer to the running instance via CDP
  const browserURL = `http://127.0.0.1:${port}`;
  const browser = await puppeteer.connect({ browserURL });
  
  // Create a new tab and automate
  const page = await browser.newPage();
  await page.goto("https://google.com");
  
  console.log(`Page title: ${await page.title()}`);
  
  // Clean up
  await browser.disconnect();
  console.log("Disconnected from browser.");
})();