{"record":{"id":"d11d2519e95c5d70","repo":"unclecode/crawl4ai","slug":"invalid-css-selector-no-elements-found-for-css-s","errorCode":null,"errorMessage":"Invalid CSS selector , No elements found for CSS selector: {css_selector}","messagePattern":"Invalid CSS selector , No elements found for CSS selector: (.+?)","errorType":"exception","errorClass":"InvalidCSSSelectorError","httpStatus":null,"severity":"error","filePath":"crawl4ai/utils.py","lineNumber":925,"sourceCode":"\n    Returns:\n        Dict[str, Any]: Extracted content including Markdown, cleaned HTML, media, links, and metadata.\n    \"\"\"\n\n    try:\n        if not html:\n            return None\n        # Parse HTML content with BeautifulSoup\n        soup = BeautifulSoup(html, \"html.parser\")\n\n        # Get the content within the <body> tag\n        body = soup.body\n\n        # If css_selector is provided, extract content based on the selector\n        if css_selector:\n            selected_elements = body.select(css_selector)\n            if not selected_elements:\n                raise InvalidCSSSelectorError(\n                    f\"Invalid CSS selector , No elements found for CSS selector: {css_selector}\"\n                )\n            div_tag = soup.new_tag(\"div\")\n            for el in selected_elements:\n                div_tag.append(el)\n            body = div_tag\n\n        links = {\"internal\": [], \"external\": []}\n\n        # Extract all internal and external links\n        for a in body.find_all(\"a\", href=True):\n            href = a[\"href\"]\n            url_base = url.split(\"/\")[2]\n            if href.startswith(\"http\") and url_base not in href:\n                links[\"external\"].append({\"href\": href, \"text\": a.get_text()})\n            else:\n                links[\"internal\"].append({\"href\": href, \"text\": a.get_text()})\n","sourceCodeStart":907,"sourceCodeEnd":943,"githubUrl":"https://github.com/unclecode/crawl4ai/blob/7e801521428ee12509994d39151006f64055ebe3/crawl4ai/utils.py#L907-L943","documentation":"Raised by get_content_of_website (crawl4ai/utils.py:925) as InvalidCSSSelectorError when a css_selector was supplied to the HTML extraction helper but BeautifulSoup's body.select(css_selector) returned zero elements. Note the message is slightly misleading: the selector may be syntactically valid; it simply matched nothing in the parsed <body> (or the page has no <body>, making body None and the select fail). It exists so callers learn their extraction selector did not match the fetched HTML.","triggerScenarios":"Calling get_content_of_website(url, html, css_selector=\"main.article\") where the HTML contains no <main class=\"article\"> element; using a selector valid for the rendered DOM but the passed html is pre-JavaScript markup; passing a selector targeting elements inside <head> (body.select never sees them); passing malformed selectors like \"div[\" that BeautifulSoup cannot parse.","commonSituations":"Scraping SPAs where content is injected by JS after the static HTML was fetched; site redesigns that rename container classes; typos in configured selectors (e.g. missing dot for class); pages that return a captcha/consent wall instead of expected content so the selector matches nothing.","solutions":["Verify the selector against the exact HTML string being passed (open it or print soup.body.prettify()) — the DOM you select on is the static parsed body, not the rendered page.","Loosen the selector (\"article\" instead of \"div.article-content.prose\") or provide a fallback list of selectors tried in order.","For JS-rendered content, fetch via AsyncPlaywrightCrawlerStrategy / the main AsyncWebcrawler with js_code or wait_for, then pass the rendered HTML (or use CrawlerRunConfig.css_selector which handles this in the pipeline).","Validate the selector syntax first with soup.select on the soup object and catch InvalidCSSSelectorError to degrade gracefully."],"exampleFix":"// before\nresult = get_content_of_website(url, html, css_selector=\"main.post-content\")\n\n// after\nfrom crawl4ai.utils import InvalidCSSSelectorError\nfor sel in (\"main.post-content\", \"article\", \"body\"):\n    try:\n        result = get_content_of_website(url, html, css_selector=sel)\n        break\n    except InvalidCSSSelectorError:\n        continue","handlingStrategy":"validation","validationCode":"from bs4 import BeautifulSoup\n\ndef selector_matches(html: str, css_selector: str) -> bool:\n    soup = BeautifulSoup(html, \"html.parser\")\n    body = soup.body or soup\n    try:\n        return bool(body.select(css_selector))\n    except Exception:\n        return False","typeGuard":null,"tryCatchPattern":"from crawl4ai.utils import InvalidCSSSelectorError\ntry:\n    content = get_content_of_website(url, html, css_selector=sel)\nexcept InvalidCSSSelectorError as e:\n    logger.warning(\"selector %r matched nothing: %s\", sel, e)\n    content = get_content_of_website(url, html)  # fallback: full body","preventionTips":["Validate selectors against the fetched static HTML before extraction","Keep a prioritized list of fallback selectors per site template","Log the saved HTML when a selector fails to catch site-redesign drift early"],"tags":["css-selector","html-parsing","beautifulsoup","crawl4ai"],"backgroundTag":null,"analyzedSha":"7e801521428ee12509994d39151006f64055ebe3","analyzedAt":"2026-08-14T20:46:20.673Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}