seleniumbase / SeleniumBase

📊 Python's all-in-one framework for web crawling, scraping, testing, and reporting. Supports pytest. UC Mode provides stealth. Includes many tools.
https://seleniumbase.io
MIT License
4.46k stars 910 forks source link

How to add saved cookies to a new browser #2676

Closed chenhaijun02 closed 2 months ago

chenhaijun02 commented 2 months ago

Hi,Michael : After I logged in and saved the cookie, I tried to add the cookie to the browser the next time I visited, but I used sb.add_cookies(cookies) & sb.drvier.add_cookie(cookies) cannot be added successfully ` if os.path.exists(get_path(f"/.auth/{user}.json")) and int( time.time() - os.path.getctime(get_path(f"/.auth/{user}.json"))) < 86400: sb.driver.delete_all_cookies() with open(get_path(f"/.auth/{user}.json")) as f: cookies = json.load(f) sb.add_cookies(cookies) sb.drvier.add_cookie(cookies) sb.open(login_url)

    sb.switch_to_newest_window()
    sb.click(HcpConfirmPage.onetrust)
else:
    sb.driver.delete_all_cookies()
    sb.maximize_window()
    sb.open(login_url)
    sb.switch_to_newest_window()
    sb.click(HcpConfirmPage.onetrust)

    LoginPage().login_to_system(sb, user, password)
    cookies = sb.driver.get_cookies()
    with open(get_path(f"/.auth/{user}.json"), "w") as f:
        json.dump(cookies, f, indent=4)

yield sb`

Did I miss something? Best wishes

WaterLoran commented 2 months ago

Based on my analysis and speculation, To add this cookie to the browser, you must first initialize the browser successfully before it can be added. However, it seems that your code has not yet initialized the browser, so you added the cookie directly to the driver The above is my guess, but I don't know how to properly initialize a browser

mdmintz commented 2 months ago

The cookie methods:

self.save_cookies(name="cookies.txt")
self.load_cookies(name="cookies.txt")
self.delete_all_cookies()  # Duplicate: self.clear_all_cookies()
self.delete_saved_cookies(name="cookies.txt")
self.get_saved_cookies(name="cookies.txt")
self.get_cookie(name)
self.get_cookies()
self.add_cookie(cookie_dict)
self.add_cookies(cookies)

For more details on those, see seleniumbase/seleniumbase/fixtures/base_case.py.

Note that you have to be on the same origin/domain before you can add cookies to it. I added an example here: https://github.com/seleniumbase/SeleniumBase/issues/2652#issuecomment-2032853857