跳转到内容
Multilogin帮助中心

Playwright 自动化示例

使用 Playwright,通过 JavaScript 或 Python 自动化 Multilogin Mimic 浏览器配置文件。以下示例使用 Multilogin API 令牌,启动已启用 Playwright 的现有配置文件,将 Playwright 连接到运行中的浏览器,打开网页并保存截图。

执行脚本时,请保持 Multilogin 应用运行。Playwright 适用于 Mimic 浏览器配置文件;旧版 Stealthfox 配置文件不支持 Playwright。

你可以使用 Playwright 自动化操作 Mimic 浏览器配置文件,用于网页抓取。请注意,Multilogin 不支持 Stealthfox 的 Playwright 自动化。

开始自动化前,请先查看:自动化脚本入门。

开始之前

JavaScript

  1. 从官方网站下载并安装 Node.js
  2. 确认 Node.js 和 npm(Node 包管理器)已正确安装:
node -v 
npm -v
  1. 创建项目目录,运行以下命令初始化新的 Node.js 项目,并创建 package.json 文件: 
npm init -y
  1. 为项目安装 Playwright 依赖: 
npm install playwright
  1. 安装 Axios:
npm install axios
  1. 将你的值填入脚本中的以下变量:
    1. API_TOKEN:你的 Multilogin API 令牌
    2. folder_id、profile_id:参考 DevTools(图形界面)或 Postman 指南查找这些值

Python

  1. 安装以下 Python 库:
    1. requests
    2. playwright
  2. 安装所需的浏览器二进制文件:
playwright install
  1. 将你的值填入脚本中的以下变量:
    1. API_TOKEN:你的 Multilogin API 令牌
    2. FOLDER_ID、PROFILE_ID:参考 DevTools(图形界面)或 Postman 指南查找这些值

需要配置文件 ID?可以直接在 Multilogin 界面中复制。操作方法:如何在 Multilogin 中复制配置文件 ID。

运行脚本

JavaScript

  1. 启动应用,以便启动配置文件
  2. 确认 Playwright 与当前 Mimic 内核版本兼容。请查看 Playwright 和 Mimic 的更新说明
  3. 运行包含自动化代码的 .js 文件

脚本示例

const { chromium } = require('playwright');
const axios = require('axios');

const HEADERS =  {
  "Content-Type": "application/json",
  "Accept": "application/json",
};
// Insert your automation token in the variable below
const API_TOKEN = "";
// Insert the Folder ID and the Profile ID below
const folder_id = "";
const profile_id = "";

async function start_browserProfile(){
  // Add the automation token to the request headers
  HEADERS.Authorization = 'Bearer ' + API_TOKEN;
  // Launch a profile defining "Playwright" as automation type
  const profileLaunch_URL = `https://launcher.mlx.yt:45001/api/v2/profile/f/${folder_id}/p/${profile_id}/start?automation_type=playwright&headless_mode=false`;
  try {
    const response = await axios.get(profileLaunch_URL, { headers: HEADERS });
    const browserURL = `http://127.0.0.1:${response.data.data.port}`;
    // if you prefer to connect with browserWSEndpoint, try to get the webSocketDebuggerUrl by following request
    // const {data : {webSocketDebuggerUrl}} = await axios.get(`${browserURL}/json/version`)
    const browser = await chromium.connectOverCDP(browserURL,{timeout:10000});
    const context = browser.contexts()[0];
    const page = await context.newPage();
    await page.goto("https://multilogin.com/");
    await page.screenshot({path: "example.png"});
    await page.close();
    // Disconnect Playwright so the script can exit
    await browser.close();
    // Stop the profile
    await axios.get(`https://launcher.mlx.yt:45001/api/v1/profile/stop/p/${profile_id}`, { headers: HEADERS });
  } catch (error) {
    console.log("Error:", error.message);
    if (error.response) {
      console.log("Response data:", error.response.data);
    }
  }
};

start_browserProfile();

Python

  1. 启动应用,以便启动配置文件
  2. 确认 Playwright 与当前 Mimic 内核版本兼容。请查看 Playwright 和 Mimic 的更新说明
  3. 运行包含自动化代码的 .py 文件

脚本示例

import requests
import time
from playwright.sync_api import sync_playwright

HEADERS = {"Accept": "application/json", "Content-Type": "application/json"}

# TODO: Insert your automation token in the variable below
API_TOKEN = ""
# TODO: Insert the Folder ID and the Profile ID below
FOLDER_ID = ""
PROFILE_ID = ""

HEADERS["Authorization"] = f"Bearer {API_TOKEN}"

def start_profile():
    with sync_playwright() as pw:
        resp = requests.get(
            f"https://launcher.mlx.yt:45001/api/v2/profile/f/{FOLDER_ID}/p/{PROFILE_ID}/start?automation_type=playwright&headless_mode=false",
            headers=HEADERS)
        resp_json = resp.json()
        if resp.status_code != 200:
            print(f"\nError while starting profile: {resp.text}\n")
            return
        else:
            print(f"\nProfile {PROFILE_ID} started.\n")
            browserPort = resp_json["data"]["port"]
            browserURL = f"http://127.0.0.1:{browserPort}"
            # if you prefer to connect with browserWSEndpoint, try to get the webSocketDebuggerUrl by following request
            # response = requests.get(f'{browserURL}/json/version')
            # browser_ws_endpoint = response.json()["webSocketDebuggerUrl"]
            browser = pw.chromium.connect_over_cdp(endpoint_url=browserURL)
            context = browser.contexts[0]
            page = context.new_page()
            page.goto('https://www.multilogin.com')
            time.sleep(5)
            page.screenshot(path='example.png')
            page.close()
            browser.close()
            # Stop the profile
            requests.get(f"https://launcher.mlx.yt:45001/api/v1/profile/stop/p/{PROFILE_ID}", headers=HEADERS)
            print(f"\nProfile {PROFILE_ID} stopped.\n")

start_profile()

随时掌握最新动态

获取最新动态,交流经验,了解实际使用场景。

获取产品更新Telegram频道向其他用户提问Telegram聊天查看使用场景Discord社区