請教大神們為什我用Playwright取到的cookie值跟在瀏覽器F12中cookie欄位的值會不一樣呢?有解嗎?
我觀察過一樣是登入後去看從Playwright啟動的chrome瀏覽器中看到的值跟python中取到的值會不一樣的?
到底是哪裡出問題了呢?
因為我去下載這個文件是利用request去下載
但是headers中裡面需要帶上Cookie': f'JSESSIONID=這個值
才可以完整下載的到正確的檔案.
如果JSESSIONID=這個值是錯誤的
雖然響應值一給的是200
但是會發給你一個假的文件檔案.
rom playwright.sync_api import Playwright, sync_playwright, expect
def get_cookie_value(playwright: Playwright) -> None:
# 使用Playwright的chromium瀏覽器,並設定為非無頭模式(headless=False),啟動瀏覽器
browser = playwright.chromium.launch(headless=False)
# 創建一個新的瀏覽器上下文(context),這可以看作是一個新的瀏覽器窗口或標籤頁
context = browser.new_context()
# 在這個上下文中創建一個新的頁面(標籤頁)
page = context.new_page()
# 導航到指定的URL
page.goto("https://tw.yahoo.com/login?service=tw.yahoo.com/rvice%2Feservice.jsp%3F7")
page.get_by_placeholder("帳號").fill("A111")
page.get_by_placeholder("密碼").fill("9998")
# 在具有"登入"按鈕角色的元素中點擊
page.get_by_role("button", name="登入").click()
page.frame_locator("internal:attr=[title=\"menuFrame\"i]").get_by_role("link", name="目錄").click()
page.wait_for_load_state("networkidle")
# 從 Cookies 中獲取 JSESSIONID 的值
cookies = context.cookies()
jsessionid = next((cookie for cookie in cookies if cookie['name'] == 'JSESSIONID'), None)
# 關閉上下文
# context.close()
# browser.close()
if jsessionid:
return jsessionid['value']
else:
return None
with sync_playwright() as playwright:
# 獲取 JSESSIONID 的值
jsessionid = get_cookie_value(playwright)
print(f'JSESSIONID: {jsessionid}')