如何实现网站自动登录
假设您想实现网站工作流程的自动化。大多数情况下,您会在进行任何其他操作之前先登录网站。您也可以将这个操作自动化!在本文中,您将学习如何编写一个简单的自动化脚本,它可以自动为您登录网站。
本文旨在指导您逐步创建脚本。如果您想参考完整的脚本,请直接滚动到文末。
步骤 1:准备IDE或类似软件
您需要一些工具来编写脚本。使用什么工具取决于您,但我们建议使用IDE。请按照以下文章中的前4个步骤操作:自动化脚本入门。
步骤 2:创建连接到API脚本并定义函数
在此步骤中,您需要使脚本与API协同工作。脚本将包含:
- API端点
- 凭证变量
- 定义了登录、打开和关闭配置文件的功能
- 已导入模块,包括
requests、hashlib和time。一些与Selenium相关的模块也会被包含进来。 - 登录请求
请使用以下模板:
import requests
import hashlib
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_BASE = "https://api.multilogin.com"
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 account information in both variables below
USERNAME = ""
PASSWORD = ""
# TODO: Insert the Folder ID and the Profile ID below
FOLDER_ID = ""
PROFILE_ID = ""
def signin() -> 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
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 = signin()
HEADERS.update({"Authorization": f"Bearer {token}"})该模板与Selenium自动化示例类似,只是开头导入了以下模块(我们需要用它来进行数据抓取):
from selenium.webdriver.common.by import By
步骤 3:选择要抓取数据的网页
您可以使用任何包含登录页面的网站。但对于本指南,我们建议您尝试此页面——它非常适合练习自动化任务:Login Page。
步骤 4:寻找目标信息
在我们的例子中,它将是用于输入凭据的文本框和登录按钮:

我们将在此页面显示所有3个元素。您可以执行以下操作:
- 在浏览器中打开开发者工具。以下是基于Chromium和Firefox的浏览器的操作方法:
- Windows和Linux :按
Ctrl + Shift + I - macOS :按
Cmd + Option + I
- Windows和Linux :按
- 请确保您位于“元素”选项卡上。
- 使用搜索快捷键查找目标值
- Windows和Linux :
CTRL + F - macOS :
Cmd + F
- Windows和Linux :
- 找到你需要用于数据抓取的值。在本例中,它将是以下值:
-
id="username"表示用户名文本字段 -
id="password"代表密码文本字段 - 登录按钮的
class="radius"
-
- 在“元素”选项卡中选择带有标签的元素
- 单击选中的值,然后复制
id或class属性的值。例如,如果您看到id="username",则需要复制username - 把这个数值记下来—您以后会用到的。

步骤 5:返回IDE并添加新的代码字符串
- 返回到您选择的IDE(例如, VS Code)
- 点击代码字段,添加一个变量,用于打开配置文件并执行操作:
driver = start_profile() - 添加
driver.get(“<您的网站>”)。在本例中,它将是以下命令:driver.get("https://the-internet.herokuapp.com/login") - 现在我们需要给脚本一些延迟,让它在打开网页5秒后尝试执行其他命令:
time.sleep(5)
步骤 6:编写脚本以查找元素
使用以下命令查找元素: driver.find_element(By.<页面上的属性>, "<元素>") 。它会告诉脚本要在页面上查找什么。在我们的用例中,我们复制了几个id和class属性的值。请从下面的列表中添加相应的字符串:
- 在用户名文本字段中添加以下字符串:
driver.find_element(By.ID, "username") - 在密码文本字段中添加以下字符串:
password = driver.find_element(By.ID, "password") - 在登录按钮中添加以下字符串:
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:告诉脚本该做什么
我们已经告诉脚本它应该检测页面上的哪些内容。现在我们要告诉脚本添加凭据并登录页面。您将使用以下函数来实现:
- 使用
send_keys()函数指定要在文本字段中输入的符号 -
click()函数模拟鼠标左键点击
在我们的用例中,您可能已经注意到,网站声明了以下凭据值:
- 用户名是
tomsmith -
SuperSecretPassword!密码
我们需要告诉脚本输入这些值并点击登录按钮。以下是代码字符串:
login.send_keys("tomsmith")
password.send_keys("SuperSecretPassword!")
button.click()步骤 8:用文本通知完成脚本
脚本已准备就绪。您可以继续进行后续准备工作并运行脚本,但我们建议您添加print()函数,以便在脚本成功执行后通知您。请考虑一下该函数的文本内容,并将其添加到脚本末尾:
print("Signed in")虽然是可选的,但你也可以在print()之后添加stop_profile()函数。我们建议不要使用它,因为该字符串偏离了脚本的本意。
步骤 9:运行脚本前先准备好脚本
- 安装以下Python库(更多详情请参阅您的IDE文档):
requests库Selenium库
- 请将您的值代入脚本中的以下变量:
步骤 10:运行脚本
- 打开桌面应用程序(如果您使用的是网页界面,则连接agent app)。
- 默认情况下,以下脚本适用于Mimic 。要将其用于Stealthfox ,请将以下行中的
options=ChromiumOptions()替换为options=Options():driver = webdriver.Remote(command_executor=f'{LOCALHOST}:{selenium_port}', options=ChromiumOptions()) - 运行包含自动化代码的
.py文件
要在 VS Code 中运行脚本,请点击“运行”→“不调试运行”(或“开始调试”)。
如果一切操作正确,您将在终端中看到结果。您还会注意到配置文件中已登录帐户。

笔记
现在一切就绪!你并不局限于这些选项。Python 和Selenium是非常灵活的工具,它们还有更大的潜力。以下是一些提示:
- 您可以根据特定条件强制脚本等待(例如,脚本会等待页面上出现特定元素)。您可以在相应的Selenium文档中了解更多信息: Waiting Strategies
- 您可以将此脚本与以下文章中的脚本结合起来: Web scraping with Selenium 101。这将为您的自动化项目奠定良好的基础!
- Selenium的实现方式不止一种。请查看其帮助中心了解更多详情:Selenium Documentation
完整脚本
import requests
import hashlib
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_BASE = "https://api.multilogin.com"
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 account information in both variables below
USERNAME = ""
PASSWORD = ""
# TODO: Insert the Folder ID and the Profile ID below
FOLDER_ID = ""
PROFILE_ID = ""
def signin() -> 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
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 = signin()
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")本文包含第三方链接,我们并未正式认可这些链接。