# /// script # requires-python = ">=3.10" # dependencies = ["crawl4ai==0.9.6"] # /// """Sign in to quotes.toscrape.com once, save the browser's cookies and storage to a file, and read the site as the signed-in user on later runs. uv run login.py The first run signs in and writes ~/crawl4ai/state/quotes.json; later runs load it and skip the sign-in. Delete the file to sign in again. """ import asyncio from pathlib import Path from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode SITE = "https://quotes.toscrape.com" STATE = Path.home() / "crawl4ai" / "state" / "quotes.json" READ = CrawlerRunConfig(cache_mode=CacheMode.BYPASS, verbose=False) # Fill in the form and submit it; the delay lets the post-login page load. SIGN_IN = CrawlerRunConfig( cache_mode=CacheMode.BYPASS, verbose=False, session_id="login", js_code=""" document.querySelector('#username').value = 'demo'; document.querySelector('#password').value = 'demo'; document.querySelector('input[type=submit]').click(); """, delay_before_return_html=3, ) async def save_state(page, context, **kwargs): # Runs before Crawl4AI reads the page: once signed in, save the session. if "/logout" in await page.content(): await context.storage_state(path=str(STATE)) return page async def main(): if not STATE.exists(): STATE.parent.mkdir(parents=True, exist_ok=True, mode=0o700) async with AsyncWebCrawler(config=BrowserConfig(headless=True, verbose=False)) as crawler: crawler.crawler_strategy.set_hook("before_return_html", save_state) await crawler.arun(f"{SITE}/login", config=SIGN_IN) if not STATE.exists(): raise SystemExit("sign-in failed") STATE.chmod(0o600) print(f"signed in; saved {STATE}") async with AsyncWebCrawler(config=BrowserConfig(headless=True, verbose=False, storage_state=str(STATE))) as crawler: page = await crawler.arun(f"{SITE}/", config=READ) print("signed in:", "Logout" in page.markdown.raw_markdown) asyncio.run(main())