NEWStandard createTask and in.php APIs. Change the address and you are connected.View API docs
GATESOLVER

Web scraping

How do I strip HTML tags from scraped text?

Parse the fragment with an HTML parser and ask for its text, after removing script and style elements; then decode entities and collapse whitespace. A regex looks quicker but breaks on real pages.

The direct answer

Let an HTML parser do it. In Python, BeautifulSoup(fragment, "html.parser").get_text(" ", strip=True) returns the text with tags removed and a space between blocks. In JavaScript, parse with DOMParser or read textContent from an element. Before extracting, delete script, style and noscript elements, whose contents are text to a parser but not to a reader. Finish by normalizing whitespace.

A Python function you can reuse

import re
from bs4 import BeautifulSoup, Comment

BLOCK_TAGS = ("p", "div", "li", "br", "h1", "h2", "h3", "tr")

def readable_text(fragment: str) -> str:
    tree = BeautifulSoup(fragment, "html.parser")
    for junk in tree(["script", "style", "noscript", "template"]):
        junk.decompose()
    for note in tree.find_all(string=lambda s: isinstance(s, Comment)):
        note.extract()
    for block in tree.find_all(BLOCK_TAGS):
        block.insert_after("\n")
    raw = tree.get_text()
    raw = raw.replace("\xa0", " ")
    raw = re.sub(r"[ \t]+", " ", raw)
    raw = re.sub(r"\n\s*\n+", "\n\n", raw)
    return raw.strip()

Inserting a newline after block elements keeps paragraph and list structure, which plain get_text() flattens. Entities such as & and é are already decoded by the parser, and the non-breaking space is turned into a normal one so later splits behave.

Why not a regular expression?

re.sub(r"<[^>]+>", "", html) is tempting and works on tidy snippets. On real pages it fails in several ways:

  • Script and style contents stay behind, so CSS rules and JavaScript end up in your text.
  • A > inside an attribute value (common in inline event handlers) cuts a tag in half.
  • Comments, CDATA sections and conditional comments leak through.
  • Entities stay encoded unless you also unescape them, and unescaping before stripping can turn escaped text like &lt;b&gt; into a fake tag.
  • Words glue together across tags: <td>Red</td><td>Large</td> becomes "RedLarge".

A regex is acceptable only for small, known, trusted fragments, such as a single span you generated yourself.

In JavaScript

function plainTextOf(markup) {
  const parsed = new DOMParser().parseFromString(markup, "text/html");
  parsed.querySelectorAll("script, style, noscript").forEach((n) => n.remove());
  return (parsed.body.textContent || "").replace(/\s+/g, " ").trim();
}

In a browser, innerText on a live element respects CSS and returns roughly what a person sees, including line breaks for blocks, while textContent returns every text node, hidden ones included. In Node.js there is no DOMParser; Cheerio gives you $(el).text() with similar results.

Whitespace and Unicode cleanup

Once tags are gone, the text still carries layout leftovers. Indentation from the source becomes runs of spaces, and line breaks inside paragraphs split sentences. Collapse spaces and tabs to one space, then reduce three or more newlines to two. Watch for invisible characters as well: zero-width spaces (U+200B), soft hyphens (U+00AD) and byte order marks sneak into scraped text and break exact matching and deduplication. Removing them, and applying Unicode normalization with unicodedata.normalize("NFC", text) in Python or text.normalize("NFC") in JavaScript, makes identical strings compare as identical.

Text inside attributes

Some useful text never appears between tags. Product names hide in title and aria-label attributes, and image descriptions in alt. A tag stripper drops all of these with the markup. If they matter, read them before flattening and append them to the text or store them in their own fields.

Keep what carries meaning

Stripping everything can throw away information. Before flattening, decide what to keep:

  • Links: collect href values separately if you need them.
  • Line breaks and list items: preserve them as newlines for text that people will read.
  • Tables: extract rows and cells into a structure instead of a run of text.
  • Alt text: images may hold the only description of a product feature.

Scrapy and other frameworks

Frameworks ship helpers for this. In Scrapy, selectors can return all text nodes with .xpath("string()") or ::text, and the w3lib package that Scrapy depends on includes a tag removal function. They follow the same rules: parser based, entity aware. Check each helper's handling of script content, since some keep it.

Watch for text that is not content

If the stripped result reads "Please verify you are human" or "Enable JavaScript and cookies to continue", the scraper received a challenge page, not the article. Detect that before storing text, otherwise your dataset fills with copies of the same notice. The question why websites block automated requests explains why those pages appear, and the API docs show how to solve the widget when it is a CAPTCHA.

Common questions

Does get_text decode HTML entities?

Yes. The parser turns named and numeric entities into their characters while building the tree.

How do I keep line breaks when stripping tags?

Insert newlines after block elements before extracting, or pass "\n" as the separator to get_text.

Why does my text contain JavaScript code?

Script elements were not removed first. Decompose script, style and noscript tags before extracting text.

What is the difference between innerText and textContent?

innerText follows CSS and skips hidden text; textContent returns every text node regardless of styling.

Is lxml faster for this?

Usually. lxml.html with text_content() is quick, but remove script and style elements first there too.

Keep reading