Playwright setting cookies not working in python

101 Views Asked by At

I'm trying to use python to add cookies to the browser in playwright, when I print BrowserContext cookies, I can see the cookie that I added, but when I'm checking it from the browser, It doesn't exists. How can I tell the browser to add cookies from browser context? here is my code :

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless = False,devtools=True)
    context = browser.new_context()
    page = context.new_page()
    page.goto("https://crawler-test.com/")
    
    # defining a random cookie
    cookies = [{'name': 'temp', 'value': 'temp', 'domain': 'temp.com', 'path': '/'}]
    
    # adding cookie to the browser context
    context.add_cookies(cookies)

    # printing cookies
    print(context.cookies())

    browser.close()

And here is the output is see in the terminal :

[{'name': '_ga_78MMTFSGVB', 'value': 'GS1......', 'domain': '.crawler-test.com', 'path': '/', 'expires': 1 'httpOnly': False, 'secure': False, 'sameSite': 'Lax'}, 
{'name': '_ga', 'value': 'GA1......', 'domain': '.crawler-test.com', 'path': '/', 'expires': 1, 'httpOnly': False, 'secure': False, 'sameSite': 'Lax'}, 
{'name': '_gid', 'value': 'GA1.......', 'domain': '.crawler-test.com', 'path': '/', 'expires': 1, 'httpOnly': False, 'secure': False, 'sameSite': 'Lax'}, 
{'name': '_gat_UA-7097885-11', 'value': '1', 'domain': '.crawler-test.com', 
'path': '/', 'expires': 1, 'httpOnly': False, 'secure': False, 'sameSite': 'Lax'}, 
{'name': 'temp', 'value': 'temp', 'domain': 'temp.com', 'path': '/', 'expires': -1, 'httpOnly': False, 'secure': False, 'sameSite': 'Lax'}]

As you can see the desired cookie is successfully added to the browser context, but when I check the cookies from the browser, I don't see the added cookies :

enter image description here

1

There are 1 best solutions below

0
Mohsen_Fatemi On

The problem is with the domain, It should match the website url. I wrongly set it to be 'temp.com' which doesn't match the url of the website. It should be '.crawler-test.com'. When I changed the code the cookie has been successfully added.

cookies = [{'name': 'temp', 'value': 'temp', 'domain': '.crawler-test.com', 'path': '/'}]