跳转到内容
Multilogin帮助中心

如何自动登录网站

本文介绍如何使用 Python、Selenium 和 Multilogin API,在 Multilogin 浏览器配置文件中自动登录网站。

你将连接 Multilogin、启动浏览器配置文件、查找网站的登录字段、输入凭据,并提交登录表单。

本文介绍浏览器配置文件中的网站自动化。要自动化云手机中的原生 Android 应用,请改用 ADB 或 Appium。

本文会带你逐步编写脚本。如果想参考完整脚本,可以直接滚动到末尾。

开始前,请确保已准备好:

  • 已安装 Python 和 IDE
  • 已安装 requests 和 selenium modules
  • 一个可用的 Multilogin 浏览器配置文件
  • 文件夹 ID 和配置文件 ID
  • 已打开 Multilogin 桌面应用,或已连接代理程序
  • 所用套餐拥有自动化访问权限

第 1 步:准备 IDE 或类似软件

你需要用软件来编写脚本。可以自行选择,我们建议使用 IDE。请先完成以下文章中的前 4 步:自动化脚本入门。

第 2 步:编写连接 API 的脚本并定义函数

这一步需要让脚本使用 API。脚本将包括:

  • API 端点
  • 用于自动化令牌的变量
  • 用于打开和关闭配置文件的函数
  • 导入的模块,包括 requests、hashlib、time,以及一些 Selenium 相关模块
  • 包含令牌的 Authorization 请求头

使用以下模板:

import requests
import time
from selenium import webdriver
from selenium.webdriver.chromium.options import ChromiumOptions
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By

MLX_LAUNCHER = "https://launcher.mlx.yt:45001/api/v1"
MLX_LAUNCHER_V2 = (
    "https://launcher.mlx.yt:45001/api/v2"  # recommended for launching profiles
)
LOCALHOST = "http://127.0.0.1"
HEADERS = {"Accept": "application/json", "Content-Type": "application/json"}
# TODO: Insert your token in the variable below
API_TOKEN = ""
# TODO: Insert the Folder ID and the Profile ID below
FOLDER_ID = ""
PROFILE_ID = ""


def start_profile() -> webdriver:
    r = requests.get(
        f"{MLX_LAUNCHER_V2}/profile/f/{FOLDER_ID}/p/{PROFILE_ID}/start?automation_type=selenium",
        headers=HEADERS,
    )
    response = r.json()
    if r.status_code != 200:
        print(f"\nError while starting profile: {r.text}\n")
    else:
        print(f"\nProfile {PROFILE_ID} started.\n")
    selenium_port = response["data"]["port"]
    driver = webdriver.Remote(
        command_executor=f"{LOCALHOST}:{selenium_port}", options=ChromiumOptions()
    )
    # For Stealthfox profiles use: options=Options()
    # For Mimic profiles use: options=ChromiumOptions()
    return driver


def stop_profile() -> None:
    r = requests.get(f"{MLX_LAUNCHER}/profile/stop/p/{PROFILE_ID}", headers=HEADERS)
    if r.status_code != 200:
        print(f"\nError while stopping profile: {r.text}\n")
    else:
        print(f"\nProfile {PROFILE_ID} stopped.\n")

token = API_TOKEN
HEADERS.update({"Authorization": f"Bearer {token}"})

此模板与 Selenium 自动化示例相似,但开头额外导入了以下模块。我们从 Selenium 导入 By,让脚本可以在页面上查找用户名字段、密码字段和登录按钮。

from selenium.webdriver.common.by import By

第 3 步:选择要自动登录的网页

可以使用任何包含登录页面的网站,但本文建议使用这个适合练习自动化任务的页面:登录页面。

第 4 步:查找登录表单元素

本例中的元素是登录字段和登录按钮:

演示网站登录表单中标出的 Username、Password 和 Login 控件

我们会获取页面上的全部 3 个元素。操作如下:

  1. 在浏览器中打开 DevTools。Chromium 和 Firefox 内核浏览器的打开方法如下:
    1. Windows 和 Linux:按 Ctrl + Shift + I
    2. macOS:按 Cmd + Option + I
  2. 确保已打开“Elements”选项卡
  3. 使用键盘快捷键查找元素
    1. Windows 和 Linux:CTRL + F
    2. macOS:Cmd + F
  4. 查找抓取时需要使用的值。本例中为:
    1. id="username",对应 Username 文本字段
    2. id="password",对应 Password 文本字段
    3. class="radius",对应 Login 按钮
  5. 在“Elements”选项卡中选择带标签的元素
  6. 点击选中的值,复制 id 或 class 属性的值。例如,看到 id="username" 时,需要复制 username
  7. 记下这些值,稍后会用到
演示登录页面旁的开发者工具 Elements 面板中标出的登录按钮及其选择器

第 5 步:在脚本中打开网站

  1. 返回所用的 IDE(例如 VS Code)
  2. 点击代码区域,添加用于打开配置文件并在其中执行操作的变量:driver = start_profile()
  3. 添加 driver.get(“<your website>”)。本例中的命令如下:
    driver.get("https://the-internet.herokuapp.com/login")
  4. 接下来需要添加延迟,让脚本在打开网页 5 秒后再执行其他命令:time.sleep(5)

第 6 步:查找登录字段和按钮

使用此命令查找元素:driver.find_element(By.<attribute on the page>, "<element>")。它会准确告诉脚本应在页面上查找什么。本例复制了多个 id 和 class 属性值。请添加下列代码行:

  1. 为用户名文本字段添加以下代码行:
    driver.find_element(By.ID, "username")
  2. 为密码文本字段添加以下代码行:
    password = driver.find_element(By.ID, "password")
  3. 为登录按钮添加以下代码行:
    button = driver.find_element(By.CLASS_NAME, "radius")

稍后还需要使用这些值,因此要为命令创建变量。可以自行命名,示例如下:

login = driver.find_element(By.ID, "username")
password = driver.find_element(By.ID, "password")
button = driver.find_element(By.CLASS_NAME, "radius")

第 7 步:输入凭据并点击 Login

我们已告诉脚本应在页面上查找什么。接下来要让脚本输入凭据并登录页面。需要使用以下函数:

  • send_keys(),用于指定在文本字段中输入哪些字符
  • click(),用于模拟鼠标左键点击

你可能已经注意到,本例网站提供了以下登录凭据:

  • tomsmith,用作用户名
  • SuperSecretPassword!,用作密码

需要让脚本输入这些值并点击登录按钮。代码如下:

login.send_keys("tomsmith")
password.send_keys("SuperSecretPassword!")
button.click()

第 8 步:在脚本末尾添加文本提示

脚本已准备好。你可以继续完成准备工作并运行脚本,但建议添加 print() 函数,提示登录成功。想好要显示的文本,将它添加到脚本末尾:

print("Signed in")

只有希望登录后关闭浏览器配置文件时,才添加 stop_profile()。如果后续自动化还需要使用已登录会话,就不要添加。

第 9 步:运行脚本前的准备工作

  1. 安装以下 Python 库(更多详情请参考所用 IDE 的文档):
    1. requests
    2. selenium
  2. 将自己的值填入脚本中的以下变量:
    1. API_TOKEN:你的 Multilogin API 令牌
    2. FOLDER_ID、PROFILE_ID:按照 DevTools 或 Postman 指南查找这些值

第 10 步:运行脚本

  1. 打开桌面应用(如果使用网页界面,则连接代理程序)
  2. 以下脚本默认适用于 Mimic。要用于 Stealthfox,请在以下代码行中将 options=ChromiumOptions() 替换为 options=Options():
    driver = webdriver.Remote(command_executor=f'{LOCALHOST}:{selenium_port}', options=ChromiumOptions())
  3. 运行包含自动化代码的 .py 文件

要在 VS Code 中运行脚本,请点击“Run” → “Run without debugging”(或“Start debugging”)。

如果操作正确,就能在终端看到结果,也能在配置文件中看到已登录的账户。

Python 自动化脚本旁的浏览器显示演示网站登录成功

注意事项

现在可以开始使用了!你还可以尝试更多做法。Python 和 Selenium 都很灵活,还有更多用途。以下是一些提示:

  • 可以让脚本根据特定条件等待(例如,等待某个元素出现在页面上)。详情见 Selenium 文档:等待策略
  • 可以将本脚本与以下文章中的脚本结合使用:Selenium 网页抓取入门。这会是自动化项目的良好起点!
  • Selenium 还有更多用法,详情请查看其帮助文档:Selenium 文档

完整脚本

import requests
import time
from selenium import webdriver
from selenium.webdriver.chromium.options import ChromiumOptions
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By

MLX_LAUNCHER = "https://launcher.mlx.yt:45001/api/v1"
MLX_LAUNCHER_V2 = (
    "https://launcher.mlx.yt:45001/api/v2"  # recommended for launching profiles
)
LOCALHOST = "http://127.0.0.1"
HEADERS = {"Accept": "application/json", "Content-Type": "application/json"}
# TODO: Insert your token in the variable below
API_TOKEN = ""
# TODO: Insert the Folder ID and the Profile ID below
FOLDER_ID = ""
PROFILE_ID = ""


def start_profile() -> webdriver:
    r = requests.get(
        f"{MLX_LAUNCHER_V2}/profile/f/{FOLDER_ID}/p/{PROFILE_ID}/start?automation_type=selenium",
        headers=HEADERS,
    )
    response = r.json()
    if r.status_code != 200:
        print(f"\nError while starting profile: {r.text}\n")
    else:
        print(f"\nProfile {PROFILE_ID} started.\n")
    selenium_port = response["data"]["port"]
    driver = webdriver.Remote(
        command_executor=f"{LOCALHOST}:{selenium_port}", options=ChromiumOptions()
    )
    # For Stealthfox profiles use: options=Options()
    # For Mimic profiles use: options=ChromiumOptions()
    return driver


def stop_profile() -> None:
    r = requests.get(f"{MLX_LAUNCHER}/profile/stop/p/{PROFILE_ID}", headers=HEADERS)
    if r.status_code != 200:
        print(f"\nError while stopping profile: {r.text}\n")
    else:
        print(f"\nProfile {PROFILE_ID} stopped.\n")


token = API_TOKEN
HEADERS.update({"Authorization": f"Bearer {token}"})
driver = start_profile()
driver.get("https://the-internet.herokuapp.com/login")
time.sleep(5)
login = driver.find_element(By.ID, "username")
password = driver.find_element(By.ID, "password")
button = driver.find_element(By.CLASS_NAME, "radius")
login.send_keys("tomsmith")
password.send_keys("SuperSecretPassword!")
button.click()
print("Signed in")

本文包含第三方链接,我们并未对其作出官方背书。

随时掌握最新动态

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

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