playwright自動登入獲取cookie/ck

__username發表於2024-10-11

有些登入逆向起來比較麻煩,就用了自動化

import time
import json
import random
from playwright.sync_api import Playwright, sync_playwright, expect
# https://xxxx.edu.cn/appportalweb/seatspace/
"""
需要提前10分鐘獲取ck
"""

def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=True)
    context = browser.new_context()
    page = context.new_page()
    page.goto("https://xxxx.edu.cn/appportalweb/seatspace/")
    page.get_by_placeholder("職工號/學號/郵箱/別名").click()
    time.sleep(random.uniform(.5, .6))
    page.get_by_placeholder("職工號/學號/郵箱/別名").fill("20210xxxx")
    page.get_by_role("textbox", name="密碼").click()
    time.sleep(random.uniform(.5, .6))
    page.get_by_role("textbox", name="密碼").fill("xxxx2xxx24")
    time.sleep(random.uniform(.2, .3))
    page.get_by_role("button", name="登 錄").click()

    cookies = context.cookies()
    print(cookies)

    # target_names = ['IDSTGC']
    found_cookie_value = next((cookie['value'] for cookie in cookies if cookie['name'] == 'IDSTGC'), None)
    print(found_cookie_value)



    cookie_data = {'IDSTGC': found_cookie_value
                   # 新增時間
                   , 'time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                   }

    # 將資料寫入 JSON 檔案
    with open('config.json', 'w') as json_file:
        json.dump(cookie_data, json_file)

    # ---------------------
    time.sleep(random.uniform(.5, .6))

    context.close()
    browser.close()


with sync_playwright() as playwright:
    run(playwright)

相關文章