前言

最近用小伙伴提到多线程同时操作多个浏览器,每个浏览器用不同账号登录的需求。

多线程操作

以下是2个账号同时打开2个浏览器操作的示例

from playwright.sync_api import sync_playwright
from threading import Thread
# 上海悠悠 wx:283340479
# blog:https://www.cnblogs.com/yoyoketang/

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
# 上海悠悠 wx:283340479
# blog:https://www.cnblogs.com/yoyoketang/


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()

文章转自:https://www.cnblogs.com/yoyoketang/p/17426724.html