0

I created a request using python's requests and saved the cookie of the request response to cookies.json, and used playwright to add cookies to the browser context, but it was always wrong. playwright._impl._api_types. Error: cookies: expected array, got object

# Save cookie
post = session.post(url, data=data, headers=headers, proxies=proxies)
        req = post.cookies.get_dict()
        with open('cookies.json', 'w+') as f:
            save_cookies = json.dumps(req, ensure_ascii=False)
            f.write(save_cookies)

# read cookie
async def worker(browser: Browser, i: int):
    cookies = get_csrf_token_login(email_name, password)
    context = await browser.new_context()
    context.clear_cookies()
    with open('cookies.json', 'r') as f:
        cookie_test = json.load(f)
    
    await context.add_cookies(cookie_test)
    page = await context.new_page()
    await page.goto(url)
    print(await page.title())


# context
async def main():
    async with async_playwright() as playwright:
        browser = await playwright.chromium.launch(headless=False, channel="chrome")
        await asyncio.wait(
            [asyncio.create_task(worker(browser, i)) for i in range(1)],  # 创建上下文数量
            return_when=asyncio.ALL_COMPLETED,
        )
        await browser.close()

2 Answers2

0

This doesn't necessarily look like a question to me, but rather a statement. Not sure if you need help with this or just made a comment. Not sure what you refer to with get_csrf_token_login(), since the function is not defined in the code you shared. Either way, a likely solution for saving and using cookies are as example in Github:

import json

from playwright.sync_api import Playwright, sync_playwright


def on_response(response):
    if '/search/positions' in response.url and response.status == 200:
        print(response.json())

def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False, slow_mo=50)
    context = browser.new_context(user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36')
    page = context.new_page()
    page.on('response', on_response)

    context.clear_cookies()

    cookie_file = open('./export.json')
    cookies = json.load(cookie_file)


    page.goto('https://www.abcxxx.com')


    context.add_cookies(cookies)

    page.goto('https://www.abcxxx.com/search')

    try:
        page.wait_for_load_state('networkidle')
        page.click("text=next")
        page.close()

    except Exception as e:
        print("Error in playwright script.")
        page.close()

    # ---------------------
    context.close()
    browser.close()


with sync_playwright() as playwright:
    run(playwright)

However, the solution in this thread (error: playwright._impl._api_types.Error: cookies[0].sameSite: expected one of (Strict|Lax|None)) to solve the cookie error in their case was a workaround: open export.json file, replace unspecified to None and then add the cookies. Note how korykim used a for-loop to add the cookies to context. I'm assuming your version of Playwright may perhaps not need the for-loop as they did, you'll need to test and see how the cookies json file looks.

page.goto('https://www.abcxxx.com')

cookie_file = open('./export.json')
cookies = json.load(cookie_file)

for cookie in cookies:
    context.add_cookies(cookie)

page.goto('https://www.abcxxx.com/home')
0

Because your exported cookies were wrong format, so playwright don't understand it. Let return you cookies like below and try again:

[{"name": "token", "value": "+6ds5a+d65a", "domain": "https://stackoverflow.com", "path": "/"}]

Hope it can help!