xtekky/gpt4free · error · ValueError

Bad url: {url}

Error message

Bad url: {url}

What it means

Thrown by clear_cookies_for_url() in g4f/requests/__init__.py when urlparse(url).hostname returns None, meaning the passed string has no parsable host component. The function needs a hostname to match cookies against CDP cookie domains, so a host-less URL cannot be processed. It is a caller-input validation error, not a network or browser error.

Source

Thrown at g4f/requests/__init__.py:112


def get_cookie_params_from_dict(
    cookies: Cookies, url: str = None, domain: str = None
) -> list[CookieParam]:
    return [
        CookieParam.from_json(
            {"name": key, "value": value, "url": url, "domain": domain}
        )
        for key, value in cookies.items()
    ]


async def clear_cookies_for_url(
    browser: Browser, url: str, ignore_cookies: list[str] = None
):
    host = urlparse(url).hostname
    if not host:
        raise ValueError(f"Bad url: {url}")

    if ignore_cookies is None:
        ignore_cookies = []
    tab = browser.main_tab  # any open tab is fine
    cookies = (
        await browser.cookies.get_all()
    )  # returns CDP cookies :contentReference[oaicite:2]{index=2}
    for c in cookies:
        dom = (c.domain or "").lstrip(".")
        if dom and (host == dom or host.endswith("." + dom)):
            if c.name in ignore_cookies:
                continue
            await tab.send(
                nodriver.cdp.network.delete_cookies(
                    name=c.name,
                    domain=dom,  # exact domain :contentReference[oaicite:3]{index=3}
                    path=c.path,  # exact path :contentReference[oaicite:4]{index=4}
                    # partition_key=c.partition_key,  # if you use partitioned cookies

View on GitHub (pinned to 973504e177)

Solutions

  1. Inspect the url value right before the call and fix the upstream string so it is a full absolute URL including scheme and host (e.g. https://example.com).
  2. If the URL comes from configuration, correct the config entry / environment variable to include the scheme.
  3. Guard the call site with urlparse(url).hostname and skip/log when it is None.
  4. Catch ValueError locally only as a last resort, logging the offending url for diagnosis.

Example fix

// before
await clear_cookies_for_url(browser, target_url)  # target_url = ""

// after
from urllib.parse import urlparse
if urlparse(target_url).hostname:
    await clear_cookies_for_url(browser, target_url)
else:
    debug.log(f"Skipping cookie clear, no host in url: {target_url}")
Defensive patterns

Strategy: validation

Validate before calling

from urllib.parse import urlparse

def has_host(url: str) -> bool:
    return bool(urlparse(url).hostname)

Type guard

def is_clearable_url(url: str) -> bool:
    """True when clear_cookies_for_url can process this url."""
    return isinstance(url, str) and urlparse(url).hostname is not None

Try / catch

try:
    await clear_cookies_for_url(browser, url)
except ValueError as e:
    debug.log(f"Skipped cookie clearing: {e}")  # bad url is not fatal

Prevention

When it happens

Trigger: Calling await clear_cookies_for_url(browser, url) with an empty string, a relative path like "/path", a scheme-only string like "http://", or a non-URL value such as "about:blank" or "data:text/html,...". Any input where urlparse cannot extract a hostname triggers it before any browser interaction happens.

Common situations: Passing a provider base URL read from config that is empty or misconfigured; forwarding a response redirect URL or window.location value that turned out to be a blank/special page; copy-paste typos like "htp://example.com" that yield no hostname.

Related errors


AI-assisted analysis of xtekky/gpt4free@973504e177 (2026-08-14). Data as JSON: /api/errors/7e4bcf61c9222b7d. Report an issue: GitHub.