Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python web scraping libraries download web pages and extract data from their HTML. Price trackers, search indexes, and AI agents that read the web use these libraries to turn pages into structured records or clean text.
Beautiful Soup turns an HTML or XML document into a tree of Python objects that code can search and change. The library hands the raw parsing to a separate parser: Python's built-in html.parser, or lxml when it is installed. find returns the first tag that matches, and find_all returns every match. Broken markup, such as unclosed tags, still parses into a tree. Another library downloads the page first, since Beautiful Soup only parses.
Downloads / mo
289.6M
Last release
4.15.0, Jun 2026
License
MIT
Strengths
find and find_all.find_all() returns every matching tag, and find() returns the first.
Handles broken HTML.Reads pages with missing or mismatched tags.
Limitations
Default parser misreads broken pages.Install lxml, a faster parser, and use it for messy HTML.
CSS selectors only.For XPath, a way to pick page elements by path, use parsel.
Slower than lxml.For large pages, lxml on its own parses much faster.
from bs4 import BeautifulSoup
with open("index.html") as fp:
soup = BeautifulSoup(fp, 'html.parser')
soup.title.string
for link in soup.find_all('a'):
print(link.get('href'))
print(soup.get_text())
def clean_soup(soup: BeautifulSoup) -> BeautifulSoup:
"""Clean the soup by removing unwanted tags"""
for tag in soup.find_all(
[
"script",
"style",
"footer",
"header",
"nav",
"menu",
"sidebar",
"svg",
]
):
tag.decompose()
disallowed_class_set = {"nav", "menu", "sidebar", "footer"}
# clean tags with certain classes def does_tag_have_disallowed_class(elem) -> bool:
if not isinstance(elem, bs4.Tag):
return False
return any(
cls_name in disallowed_class_set for cls_name in elem.get("class", [])
)
for tag in soup.find_all(does_tag_have_disallowed_class):
tag.decompose()
return soup
def scrape_category(category_url):
try:
soup = BeautifulSoup(requests.get(BASE_URL + category_url).text)
except ConnectionError:
print("Couldn't connect to Internet! Please check your connection & Try again.")
exit(1)
# Selecting links which are in the category page links = [a.attrs.get("href") for a in soup.select("article li a")]
# ... for link in links:
try:
# ... link_soup = BeautifulSoup(requests.get(link).text)
# Remove the space occupied by Google Ads (Drop script & ins node) [script.extract() for script in link_soup(["script", "ins"])]
for code_tag in link_soup.find_all("pre"):
code_tag["class"] = code_tag.get("class", []) + ["prettyprint"]
article = link_soup.find("article")
# Now add this article to list of all articles page = Article(
title=link_soup.title.string, content=article.encode("UTF-8")
)
articles.append(page)
# Sometimes hanging. So Ctrl ^ C, and try the next link. # Find out the reason & improve this. except KeyboardInterrupt:
continue
# ...
trafilatura
Trafilatura is a Python package and command-line tool that downloads web pages and keeps their main text, dropping recurring parts such as headers, footers, and boilerplate. fetch_url downloads a page, and extract returns its text; with with_metadata=True, the result also includes the title, author, and date. Output formats include plain text, Markdown, CSV, JSON, HTML, XML, and XML-TEI, a format for text corpora. The package also finds new pages through sitemaps and RSS or Atom feeds.
Downloads / mo
12.9M
Stars
7.1K
Last release
2.3.1, Oct 2026
License
Apache-2.0
Strengths
Pulls the article text.Returns the main text with title, author, and date, minus menus and footers.
Exports Markdown, JSON, or XML.Also writes plain text.
Limitations
Skips JavaScript-loaded text.Reads static HTML only, so text added by scripts is missed.
Can miss text on unusual layouts.Short or link-heavy pages can come back incomplete.
def get_full_article(self, url: str) -> dict:
try:
import trafilatura
except ImportError as e:
raise ImportError(
"get_full_article() requires trafilatura. "
"Install it with: pip install gnews[fulltext]"
) from e
if self._proxy:
downloaded = self._download_via_proxy(url)
else:
downloaded = trafilatura.fetch_url(url)
if not downloaded:
raise NetworkError(f"Could not download article from {url}")
text = trafilatura.extract(downloaded, include_comments=False, include_tables=False)
if not text:
raise NetworkError(f"Could not extract article text from {url}")
return {"text": text, "url": url}
def scrape_text_from_url(url):
"""
Scrape the content from the URL
"""
try:
downloaded = trafilatura.fetch_url(url)
text = trafilatura.extract(downloaded, include_formatting=True)
if text is None:
return []
text_chunks = text.split("\n")
article_content = [text for text in text_chunks if text]
return article_content
except Exception as e:
print(f"Error: {e}")
scrapy
Scrapy is a crawling framework maintained by Zyte. Each spider class lists its start URLs and a parse method that pulls items from every response with CSS selectors or XPath, a way to pick page elements by their path in the document. Links that parse returns go back to a scheduler, which sends requests asynchronously, so a slow or failed page doesn't hold up the others. scrapy runspider runs a single spider file, and feed exports write the items as JSON Lines, CSV, or XML.
Downloads / mo
4.3M
Stars
65.3K
Last release
2.20.0, Nov 2026
License
BSD-3-Clause
Strengths
Concurrent requests.Sends many requests at once across mostly static sites.
Built-in cleanup and export.Pipelines check each record, and exporters write JSON or CSV.
Limitations
No JavaScript by default.Add the scrapy-playwright plugin for pages that need a browser.
More setup than a script.Each crawl starts as a project folder with spider classes.
def parse_couplets(self, response):
title = response.css('.articalTitle h2 ::text').extract_first()
lines = response.css('.articalContent::text, .articalContent *::text').extract()
output_file = open('output/' + title + '.txt', 'wb')
mid = u'〓'
end = u'◎'
for line in lines:
if (not mid in line) or (not end in line):
continue
line = line.replace(end, '').replace('|', '')
words = re.split(r"[\u200b\s]+", line, flags=re.UNICODE)
for word in words:
if len(word.strip()) == 0:
continue
couplet = word.split(mid)
if len(couplet) != 2:
logging.warning("Error while process " + word)
continue
up, down = couplet
if (not up) or (not down) or len(up) != len(down):
logging.warning("Error while process " + word)
continue
output_file.write((up + u'\n').encode('utf8'))
output_file.write((down + u'\n').encode('utf8'))
output_file.close()
def _extract_images(response):
page_has_images = response.xpath("//img")
if page_has_images:
img_df = pd.DataFrame([x.attrib for x in response.xpath("//img")])
if "src" in img_df:
img_df["src"] = [
response.urljoin(url) if isinstance(url, str) else url
for url in img_df["src"]
]
img_df = img_df.apply(lambda col: col.fillna("").str.cat(sep="@@")).to_frame().T
img_df = img_df[img_df.columns.intersection(_IMG_ATTRS)]
img_df = img_df.add_prefix("img_")
d = img_df.to_dict("records")[0]
return d
return {}
parsel
Parsel extracts data from HTML and XML with CSS selectors and XPath expressions, and from JSON with JMESPath and JSONPath, two query languages for JSON. A Selector wraps the text, css or xpath narrows it, and get or getall returns the first match or every match. re runs a regular expression on any selection. Unlike Scrapy, Parsel doesn't download pages; it parses text that another tool fetched.
Downloads / mo
3.2M
Stars
1.4K
Last release
1.12.1, Sep 2026
License
BSD-3-Clause
Strengths
CSS, XPath, and JSON queries.One Selector runs CSS or XPath on HTML, and JSON queries on JSON.
Built on lxml.Selectors run on lxml, a parser written in C.
Limitations
Doesn't download pages.Fetch the HTML with another tool first.
Can't run JavaScript.Render the page with Playwright, a browser automation tool, then parse it.
async def scrape_feed(url) -> Dict[str, datetime]:
"""scrapes atom RSS feed and returns all entries in "url:publish date" format"""
result = await SCRAPFLY.async_scrape(ScrapeConfig(url, **BASE_CONFIG, retry=True))
body = result.content
# parse as XML and drop the sitemap namespace: parsel >= 1.12 detects XML from the <?xml declaration on its own selector = Selector(text=body, type="xml")
selector.remove_namespaces()
results = {}
for item in selector.xpath("//sitemap"):
url = item.xpath("loc/text()").get()
pub_date = item.xpath("lastmod/text()").get()
results[url] = datetime.fromisoformat(pub_date)
return results
crawl4ai
crawl4ai loads pages in a browser that Playwright controls and turns them into Markdown or structured JSON for LLM pipelines. After the pip install, a setup command installs the browser once. AsyncWebCrawler opens a crawler, and arun on a URL returns a result whose markdown field contains the page text. The open source crawler, under the Apache license, also powers a hosted API from the same team.
Downloads / mo
1.3M
Stars
87.1K
Last release
0.9.5, Oct 2026
License
Apache-2.0
Strengths
Turns pages into Markdown.Renders each page in a browser, then converts it to Markdown for an LLM.
No per-page cost.Free to run at any volume when self-hosted.
Limitations
A browser per crawl.Each crawl drives a headless browser, which takes more memory than an HTTP fetch. For many URLs, arun_many runs a memory-adaptive dispatcher.
Browser installed separately.Playwright's Chromium is installed after the package, with the setup command or python -m playwright install.
import asyncio
from crawl4ai import AsyncWebCrawler
async def main():
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(url="https://news.ycombinator.com")
print(result.markdown)
asyncio.run(main())
async def fetch_page(url: str, timeout_ms: int = 60000) -> Page:
"""Fetch a page via Crawl4AI and return structured content."""
try:
async with AsyncWebCrawler() as crawler:
result = await crawler.arun(
url=url,
config=CrawlerRunConfig(
cache_mode=CacheMode.BYPASS,
page_timeout=timeout_ms,
),
)
if not result.success:
return Page(url=url, success=False, error=result.error_message, markdown="", html="", links=[])
md_obj = result.markdown
markdown_text = ""
if md_obj and hasattr(md_obj, "raw_markdown"):
markdown_text = md_obj.raw_markdown or ""
links: list[dict] = []
for scope in ("internal", "external"):
for link in (result.links or {}).get(scope, []):
href = link.get("href", "")
if href and not href.startswith("javascript:"):
links.append({"href": href, "text": link.get("text", "")[:200]})
return Page(url=url, markdown=markdown_text, html=result.html or "", links=links)
except Exception as e:
return Page(url=url, success=False, error=str(e), markdown="", html="", links=[])
async def read_url(url: str, format: str = "markdown_with_citations") -> str:
# ... global crawler
if not crawler:
await initialize_crawler()
run_config = CrawlerRunConfig(
cache_mode=CacheMode.BYPASS,
word_count_threshold=10,
excluded_tags=["nav", "footer", "header"],
markdown_generator=DefaultMarkdownGenerator(
options={"citations": True}
)
)
try:
result = await crawler.arun(url=url, config=run_config)
content = None
if format == "raw_markdown":
content = result.markdown_v2.raw_markdown
elif format == "markdown_with_citations":
content = result.markdown_v2.markdown_with_citations
elif format == "references_markdown":
content = result.markdown_v2.references_markdown
elif format == "fit_markdown":
content = result.markdown_v2.fit_markdown
elif format == "fit_html":
content = result.markdown_v2.fit_html
else:
content = result.markdown_v2.markdown_with_citations
# ... return content
except Exception as e:
error_msg = f"Error crawling URL: {str(e)}"
print(error_msg)
return json.dumps({"error": error_msg}, ensure_ascii=False)
Scrapling
Scrapling combines HTTP requests, stealth browsers that render JavaScript, parsing, and concurrent crawling in one Python library. Fetcher.get downloads a page, and css or xpath selects elements from it; adaptive tracking finds an element again after the site's markup changes. Spider classes add proxy rotation, retries, pause and resume, and exports to JSON, CSV, or XML. An MCP server, a standard interface for AI tools, lets agents run the same fetches.
Downloads / mo
919.9K
Stars
99.8K
Last release
0.5.1, Nov 2026
License
BSD-3-Clause
Strengths
Selectors survive site changes.With adaptive=True, a selector that stops matching finds its element again.
Crawls and exports built in.Runs concurrent crawls with retries and exports JSON, CSV, or XML.
Gets past bot checks.Anti-bot evasion is built in, so blocked pages need no extra tool.
Limitations
One machine per crawl.Splitting a crawl across machines needs another tool.
API still changes.Still a 0.x release, so pin the version and read release notes before upgrading.
One main maintainer.Most commits come from a single author.
def fetch_fast(url, max_chars=30000, timeout=15):
"""
Fast HTTP fetch — no JavaScript execution.
Works for most blogs and static sites.
"""
from scrapling.fetchers import Fetcher
_suppress_scrapling_logs()
page = Fetcher().get(url, timeout=timeout, stealthy_headers=True)
return extract_content(page, url, max_chars)
crawlee-python
Crawlee, from Apify, crawls sites through a set of crawler classes that share routing, storage, and proxy rotation. BeautifulSoupCrawler downloads pages over HTTP and parses them with Beautiful Soup, while PlaywrightCrawler drives a headless browser for pages that build their content with JavaScript. Each run writes its results to a storage folder in the working directory. Optional extras keep the base install small, and a TypeScript version shares the same design.
Downloads / mo
818.7K
Stars
9.7K
Last release
1.11.1, Nov 2026
License
Apache-2.0
Strengths
One API for HTTP and browsers.The same crawler code works over plain HTTP or in a full browser.
Parallel by default.Runs as many requests at once as the machine's CPU and memory allow.
Limitations
Browser crawls are slower.Use BeautifulSoupCrawler for pages that need no JavaScript.
Firecrawl turns websites into Markdown for AI agents and comes in three forms: Firecrawl Local, a single program for one machine; Firecrawl Cloud, the hosted service; and a self-hosted server. Scrape returns one page, crawl follows a site's links, and map lists its URLs. The Python SDK, installed with pip install firecrawl, works with all three, and pointing it at Firecrawl Local needs no API key. Pages that need JavaScript render in a locally installed Chrome or Chromium.
Downloads / mo
702.0K
Stars
199.8K
Last release
4.55.0, Nov 2026
License
AGPL-3.0
Strengths
Returns LLM-ready Markdown.Output keeps headings and links and needs no extra cleanup.
Limitations
Cloud-only features.Structured JSON, screenshots, browser actions, and the Agent run only on Firecrawl Cloud.
Rust for the local build.Firecrawl Local installs from crates.io and needs Rust and a C compiler.
Paid hosted API.The cloud API charges per use and has rate limits.
def _scrape_firecrawl(url: str) -> str | None:
"""Scrape *url* with Firecrawl and return clean markdown, or None on failure."""
api_key = os.environ.get("FIRECRAWL_API_KEY", "").strip()
if not api_key:
logger.debug("FIRECRAWL_API_KEY not set — skipping Firecrawl")
return None
if not _firecrawl_available:
logger.debug("firecrawl-py not installed — skipping Firecrawl")
return None
try:
app = _FirecrawlApp(api_key=api_key)
result = app.scrape_url(url, params={"formats": ["markdown"]})
markdown = result.get("markdown", "").strip()
if markdown:
logger.info("Firecrawl: successfully scraped %s (%d chars)", url, len(markdown))
return markdown
logger.warning("Firecrawl: empty markdown for %s", url)
return None
except Exception as exc:
logger.warning("Firecrawl failed for %s: %s", url, exc)
return None
FAQ
It depends on the job. Scrapy crawls large sites, crawl4ai reads pages that load content with JavaScript, and beautifulsoup4 parses HTML and has 289.6M downloads a month.
scrapy is better for crawling whole sites: it schedules requests, follows links, and exports items to JSON or CSV. beautifulsoup4 is better for searching one page, with find() for the first match and find_all() for every match. Beautiful Soup does not crawl or follow links.
crawl4ai is a free Apache-2.0 library that runs a headless browser on the user's own machines. firecrawl is a hosted API that charges per use, with a self-hostable server that takes more setup. Both return Markdown or JSON for LLM pipelines.
crawl4ai is the closest open-source match: it renders pages in a headless browser and returns Markdown or JSON, with no per-page cost when self-hosted. Scrapling and crawlee-python also render JavaScript pages.
beautifulsoup4 parses an HTML or XML page into a tree that find(), find_all(), and CSS selectors can search. It has 289.6M downloads a month, more than any other Python scraping library.
firecrawl is a hosted API, with a self-hostable server, that scrapes, crawls, and maps sites. It returns LLM-ready Markdown or structured JSON.
For coding agents
Found your web scraping library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.