Created
March 18, 2025 23:56
-
-
Save minhphong306/ba7d68e63d0c82c0045dd78d11d606ac to your computer and use it in GitHub Desktop.
Python Playwright multi thread cookie
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
import time | |
from playwright.sync_api import sync_playwright | |
import requests | |
# Biến toàn cục để lưu cookie và lock để đảm bảo thread-safe | |
cookie_storage = None | |
cookie_lock = threading.Lock() | |
# Luồng 1: Login và lấy cookie | |
def login_and_get_cookie(): | |
global cookie_storage | |
with sync_playwright() as p: | |
browser = p.chromium.launch(headless=False) # headless=False để xem quá trình | |
context = browser.new_context() | |
page = context.new_page() | |
# Thay bằng URL login của bạn | |
page.goto("https://example.com/login") | |
# Điền thông tin đăng nhập (thay bằng thông tin thật) | |
page.fill("#username", "your_username") | |
page.fill("#password", "your_password") | |
page.click("#login-button") | |
# Chờ cho đến khi đăng nhập thành công (thay bằng selector phù hợp) | |
page.wait_for_selector("#dashboard", timeout=30000) | |
# Lấy cookies từ context | |
cookies = context.cookies() | |
# Lưu cookie vào biến toàn cục một cách thread-safe | |
with cookie_lock: | |
cookie_storage = cookies | |
print("Login successful, cookies obtained:", cookies) | |
browser.close() | |
# Luồng 2: Sử dụng cookie để gọi API | |
def make_api_request(): | |
global cookie_storage | |
while True: | |
# Kiểm tra xem cookie đã được lấy chưa | |
with cookie_lock: | |
if cookie_storage is not None: | |
cookies = cookie_storage | |
else: | |
cookies = None | |
if cookies: | |
# Chuyển cookie thành định dạng phù hợp cho requests | |
cookie_dict = {cookie['name']: cookie['value'] for cookie in cookies} | |
# Thay bằng API endpoint của bạn | |
api_url = "https://example.com/api/data" | |
try: | |
response = requests.get(api_url, cookies=cookie_dict) | |
print("API Response:", response.status_code, response.text) | |
break # Thoát vòng lặp sau khi gọi API thành công | |
except Exception as e: | |
print("API request failed:", e) | |
else: | |
print("Waiting for cookies...") | |
time.sleep(2) # Chờ 2 giây trước khi thử lại | |
# Hàm main để chạy 2 luồng | |
def main(): | |
# Tạo 2 luồng | |
login_thread = threading.Thread(target=login_and_get_cookie) | |
api_thread = threading.Thread(target=make_api_request) | |
# Bắt đầu chạy các luồng | |
login_thread.start() | |
api_thread.start() | |
# Đợi cả 2 luồng hoàn thành | |
login_thread.join() | |
api_thread.join() | |
print("Both threads completed.") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment