Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

Fix Httpx close issue

Sandeep Salwanb18661ba33f8
diff --git a/browser_use/browser/browser.py b/browser_use/browser/browser.py
index ad83fd5ab..803e01848 100644
--- a/browser_use/browser/browser.py
+++ b/browser_use/browser/browser.py
@@ -422,22 +422,6 @@ class Browser:
except Exception as e:
logger.debug(f'Failed to cleanup browser in destructor: {e}')
+ # no-op because httpx clients are by their creators, not by the Browser class
async def cleanup_httpx_clients(self):
- """Cleanup all httpx clients"""
- import gc
-
- import httpx
-
- # Force garbage collection to make sure all clients are in memory
- gc.collect()
-
- # Get all httpx clients
- clients = [obj for obj in gc.get_objects() if isinstance(obj, httpx.AsyncClient)]
-
- # Close all clients
- for client in clients:
- if not client.is_closed:
- try:
- await client.aclose()
- except Exception as e:
- logger.debug(f'Error closing httpx client: {e}')
+ pass
diff --git a/browser_use/browser/tests/httpx_client_test.py b/browser_use/browser/tests/httpx_client_test.py
new file mode 100644
index 000000000..c2ce5c0da
--- /dev/null
+++ b/browser_use/browser/tests/httpx_client_test.py
@@ -0,0 +1,40 @@
+import asyncio
+import pytest
+import httpx
+
+from browser_use.browser.browser import Browser, BrowserConfig
+
+
+async def test_browser_close_doesnt_affect_external_httpx_clients():
+ """
+ Test that Browser.close() doesn't close HTTPX clients created outside the Browser instance.
+ This test demonstrates the issue where Browser.close() is closing all HTTPX clients.
+ """
+ # Create an external HTTPX client that should remain open
+ external_client = httpx.AsyncClient()
+
+ # Create a Browser instance
+ browser = Browser(config=BrowserConfig(headless=True))
+
+ # Close the browser (which should trigger cleanup_httpx_clients)
+ await browser.close()
+
+ # Check if the external client is still usable
+ try:
+ # If the client is closed, this will raise RuntimeError
+ # Using a simple HEAD request to a reliable URL
+ await external_client.head("https://www.example.com", timeout=2.0)
+ client_is_closed = False
+ except RuntimeError as e:
+ # If we get "Cannot send a request, as the client has been closed"
+ client_is_closed = "client has been closed" in str(e)
+ except Exception:
+ # Any other exception means the client is not closed but request failed
+ client_is_closed = False
+ finally:
+ # Always clean up our test client properly
+ await external_client.aclose()
+
+ # Our external client should not be closed by browser.close()
+ assert not client_is_closed, "External HTTPX client was incorrectly closed by Browser.close()"
\ No newline at end of file