最受欢迎主题: Multilogin X, Multilogin 6,
Playwright自动化示例
Playwright是一个开源自动化库,旨在测试 Web 应用程序并自动与 Web 浏览器交互。它提供对浏览器操作的全面控制,包括导航、表单填写、元素点击和从网页提取数据。
在本文中,我们将提供一个简单的脚本,启动浏览器配置文件并将其与Playwright连接起来。
您可以使用Playwright为您的网络爬虫自动Mimic浏览器配置文件。请注意, Multilogin X中尚未提供Stealthfox的Playwright 。
在你开始之前
JavaScript
- 从官方网站下载Node.js并安装
- 确保 Node.js 和 npm(Node 包管理器)已正确安装:
node -v
npm -v
- 创建一个项目目录,然后运行此命令来初始化一个新的 Node.js 项目并创建一个
package.json
文件:
npm init -y
- 安装Playwright作为你的项目的依赖项:
npm install playwright
- 安装Axios和MD5库:
npm install axios
npm install md5
Python
- 安装以下 Python 库:
- 要求
- 剧作家
- 安装必要的浏览器二进制文件:
playwright install
运行脚本
JavaScript
- 确保代理已连接,因为它使得配置文件启动成为可能
- 确保Playwright与当前的Mimic核心版本兼容 - 查看Playwright和Mimic发行说明
- 使用自动化代码运行
.js
文件
脚本示例
const { chromium } = require('playwright');
const md5 = require ('md5');
const axios = require('axios');
const HEADERS = {
"Content-Type": "application/json",
"Accept": "application/json",
};
const acc_info = {
// Insert your account information in both variables below
"email": "",
"password": md5("")
};
async function get_token() {
const signIn_URL = "https://api.multilogin.com/user/signin";
try {
const response = await axios.post(signIn_URL, acc_info, { headers: HEADERS });
return response.data.data.token;
} catch (error) {
console.log(error.message);
console.log("Response data:", error.response.data);
return false;
}
};
// Insert the Folder ID and the Profile ID below
const folder_id = "";
const profile_id = "";
async function start_browserProfile(){
const token = await get_token();
if (!token) return;
// Update HEADERS with bearer token retrived from the get_token function
HEADERS.Authorization = 'Bearer ' + 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();
} catch (error) {
console.log("Error:", error.message);
if (error.response) {
console.log("Response data:", error.response.data);
}
}
};
start_browserProfile();
Python
- 确保代理已连接,因为它使得配置文件启动成为可能
- 确保Playwright与当前的Mimic核心版本兼容 - 查看Playwright和Mimic发行说明
- 使用自动化代码运行
.py
文件
脚本示例
import hashlib
import requests
import time
from playwright.sync_api import sync_playwright
MLX_BASE = "https://api.multilogin.com"
HEADERS = {"Accept": "application/json", "Content-Type": "application/json"}
# TODO: Insert your account information in both variables below
USERNAME = ""
PASSWORD = ""
# TODO: Insert the Folder ID and the Profile ID below
FOLDER_ID = ""
PROFILE_ID = ""
def sign_in() -> str:
payload = {
"email": USERNAME,
"password": hashlib.md5(PASSWORD.encode()).hexdigest(),
}
r = requests.post(f"{MLX_BASE}/user/signin", json=payload)
if r.status_code != 200:
print(f"\nError during login: {r.text}\n")
else:
response = r.json()["data"]
token = response["token"]
return token
HEADERS["Authorization"] = f"Bearer {sign_in()}"
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()
start_profile()