前言
最近用小伙伴提到多线程同时操作多个浏览器,每个浏览器用不同账号登录的需求。
多线程操作
以下是2个账号同时打开2个浏览器操作的示例
from playwright.sync_api import sync_playwright
from threading import Thread
def do_some_thing(username, password):
playwright = sync_playwright().start()
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
page = context.new_page()
page.goto("http://127.0.0.1/login.html")
page.get_by_placeholder("请输入用户名").fill(username)
page.get_by_placeholder("请输入密码").fill(password)
page.get_by_role("button", name="立即登录 >").click()
# do ....
context.close()
browser.close()
users = [
["yoyo", "123456**"],
["yoyo2", "123456**"]
]
# 多线程,2个账号同时操作
for user in users:
thread = Thread(target=do_some_thing, args=user)
thread.start()
非无痕模式多线程
launch_persistent_context 启动的时候,如果需要多个账号同时保持登录,需设置不同的user_data_dir 用户数据目录,让用户账号数据隔离。
from playwright.sync_api import sync_playwright
from threading import Thread
def do_some_thing(username, password):
p = sync_playwright().start()
browser = p.chromium.launch_persistent_context(
# 指定本机用户缓存地址
user_data_dir=f"D:chrome_userx{username}",
# 接收下载事件
accept_downloads=True,
# 设置 GUI 模式
headless=False,
bypass_csp=True,
slow_mo=1000
)
page = browser.pages[0]
page.goto("http://127.0.0.1/login.html")
page.get_by_placeholder("请输入用户名").fill(username)
page.get_by_placeholder("请输入密码").fill(password)
page.get_by_role("button", name="立即登录 >").click()
# do ....
browser.close()
users = [
["yoyo", "123456**"],
["yoyo2", "123456**"]
]
# 多线程,2个账号同时操作
for user in users:
thread = Thread(target=do_some_thing, args=user)
thread.start()
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.fwqtg.net
相关推荐: #yyds干货盘点# LeetCode程序员面试金典:填充每个节点的下一个右侧节点指针
题目: 给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下: struct Node { int val; Node *left; Node *right; Node *next; } 填充它的每个 next 指…