Skip to content

Fix: safely create a new page if no page exists in persistent context #1211

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions crawl4ai/browser_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -963,8 +963,13 @@ async def get_page(self, crawlerRunConfig: CrawlerRunConfig):
context = self.default_context
pages = context.pages
page = next((p for p in pages if p.url == crawlerRunConfig.url), None)
if not page:
page = context.pages[0] # await context.new_page()
if not page:
# Prefer an existing, open page; otherwise create one.
if pages:
live_pages = [p for p in pages if not p.is_closed()]
page = live_pages[0] if live_pages else await context.new_page()
else:
page = await context.new_page()
else:
# Otherwise, check if we have an existing context for this config
config_signature = self._make_config_signature(crawlerRunConfig)
Expand Down
124 changes: 124 additions & 0 deletions tests/test_browser.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import asyncio
import os
import psutil
import json
from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig, CacheMode
from crawl4ai.extraction_strategy import JsonCssExtractionStrategy

async def test_persistent_context_page_creation():
# Log memory usage for debugging
process = psutil.Process(os.getpid())
print(f"Initial Memory Usage: {process.memory_info().rss // (1024 * 1024)} MB")

# Browser configuration for persistent context
browser_config = BrowserConfig(
headless=True,
java_script_enabled=True,
user_agent_mode="random",
light_mode=True,
viewport_width=1280,
viewport_height=720,
use_persistent_context=True,
verbose=True # Enable verbose logging for debugging
)

# JSON extraction schema for testing
schema = {
"name": "Test Items",
"baseSelector": "div",
"fields": [
{"name": "title", "selector": "h1", "type": "text"},
{"name": "link", "selector": "a", "type": "attribute", "attribute": "href"}
]
}

# Crawler configuration
crawler_config = CrawlerRunConfig(
cache_mode=CacheMode.BYPASS,
extraction_strategy=JsonCssExtractionStrategy(schema),
session_id="test_persistent_session",
wait_for="css:body",
simulate_user=True,
page_timeout=120000
)

async with AsyncWebCrawler(config=browser_config) as crawler:
try:
# Test 1: Initial crawl with persistent context
print("\nTest 1: Initial crawl with persistent context")
result = await crawler.arun(
url="https://example.com",
config=crawler_config
)
print("Initial Crawl Success!")
print(f"Extracted JSON: {result.extracted_content[:300]}")
print(f"Links: {len(result.links)}")

# Test 2: Multiple crawls to test session reuse
print("\nTest 2: Multiple crawls to test persistent context")
result = await crawler.arun(
url="https://example.com",
config=crawler_config
)
print("Second Crawl Success!")
print(f"Extracted JSON: {result.extracted_content[:300]}")
print(f"Links: {len(result.links)}")

# Test 3: Crawl a dynamic site with JavaScript
print("\nTest 3: Crawl dynamic site with persistent context")
result = await crawler.arun(
url="https://www.kidocode.com/degrees/technology",
config=CrawlerRunConfig(
cache_mode=CacheMode.BYPASS,
extraction_strategy=JsonCssExtractionStrategy(schema),
session_id="test_persistent_session",
js_code="""document.querySelectorAll('a').forEach(a => a.click());""",
wait_for="css:body",
page_timeout=120000
)
)
print("Dynamic Crawl Success!")
print(f"Extracted JSON: {result.extracted_content[:300]}")
print(f"Links: {len(result.links)}")

# Test 4: Additional crawl to verify session persistence
print("\nTest 4: Additional crawl to verify session persistence")
result = await crawler.arun(
url="https://example.com",
config=CrawlerRunConfig(
cache_mode=CacheMode.BYPASS,
extraction_strategy=JsonCssExtractionStrategy(schema),
session_id="test_persistent_session",
wait_for="css:body",
simulate_user=True,
page_timeout=120000
)
)
print("Additional Crawl Success!")
print(f"Extracted JSON: {result.extracted_content[:300]}")
print(f"Links: {len(result.links)}")

# Test 5: Crawl with new session
print("\nTest 5: Crawl with new session")
result = await crawler.arun(
url="https://example.com",
config=CrawlerRunConfig(
cache_mode=CacheMode.BYPASS,
extraction_strategy=JsonCssExtractionStrategy(schema),
session_id="new_session",
wait_for="css:body",
simulate_user=True,
page_timeout=120000
)
)
print("Crawl with new session Success!")
print(f"Extracted JSON: {result.extracted_content[:300]}")
print(f"Links: {len(result.links)}")
Comment on lines +48 to +116
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Relying on external sites will make the test flaky.

https://example.com and https://www.kidocode.com/... are outside your control; network hiccups or site changes will break CI.
Host minimal HTML fixtures in-repo or spin up a tiny HTTP server during the test instead.

-url="https://example.com",
+url=f"http://localhost:{port}/example_fixture.html",

Same for the dynamic JS page—serve a local file with the required anchors and script.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In tests/test_browser.py between lines 48 and 116, the tests rely on external
websites like https://example.com and https://www.kidocode.com, which can cause
flaky tests due to network issues or site changes. To fix this, replace these
external URLs with local minimal HTML fixtures stored within the repository or
start a lightweight local HTTP server during the test to serve these fixtures.
Also, for the dynamic JavaScript test, serve a local HTML file containing the
necessary anchors and scripts instead of relying on an external site.


print(f"Final Memory Usage: {process.memory_info().rss // (1024 * 1024)} MB")
except Exception as e:
print(f"Error during test: {str(e)}")
raise

Comment on lines +8 to +122
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Add real assertions – prints alone don’t validate the fix.

The test currently passes as long as no exception bubbles up; it never checks that the crawler actually reused / recreated pages as intended.
Add assertions such as:

  • assert result is not None
  • assert len(result.links) > 0
  • assert crawler._browser_context.pages length grows / stays constant according to expectations

Without these, the test won’t fail if the regression resurfaces.
Consider also asserting that the same page instance is reused between Test 1 and Test 2, and that a fresh one appears for the new session.

🤖 Prompt for AI Agents
In tests/test_browser.py between lines 8 and 122, the test uses print statements
but lacks real assertions to verify correct behavior. Add assertions after each
crawl to check that the result is not None, that the number of extracted links
is greater than zero, and that the browser context's pages list length behaves
as expected (e.g., remains constant for the same session and increases for a new
session). Also, assert that the same page instance is reused between Test 1 and
Test 2, and that a new page instance is created for the new session in Test 5.
This will ensure the test properly validates session reuse and page creation
behavior.

if __name__ == "__main__":
asyncio.run(test_persistent_context_page_creation())