Skillversitas

The get_text Method

.get_text() extracts the text of a tag and all of its descendants, concatenated into one string. It is the workhorse for turning HTML fragments into plain text, and it has useful options for separators and whitespace.

Basic Usage

from bs4 import BeautifulSoup

html = "<p>Price: <b>$9.99</b> <span>was $12</span></p>"
soup = BeautifulSoup(html, "html.parser")
print(soup.p.get_text())  # Price: $9.99 was $12

The separator Argument

By default the texts are concatenated with nothing between them, which can glue words together. Pass separator to join them explicitly:

print(soup.p.get_text(separator=" "))       # Price: $9.99 was $12
print(soup.p.get_text(separator=" | "))     # Price: | $9.99 | was $12
print(soup.p.get_text(separator="\n"))      # each text on its own line

The strip Argument

strip=True removes leading and trailing whitespace from every text fragment, which is the right default when you want clean output:

html = "<ul><li>  alpha  </li><li>beta</li></ul>"
soup = BeautifulSoup(html, "html.parser")
print(soup.ul.get_text(separator=", ", strip=True))  # alpha, beta

.text vs .get_text()

.text is a shortcut for get_text() with default arguments. Use .text for quick prints and .get_text(separator=..., strip=True) for anything you store. Note that .text ignores structure: two paragraphs become one string, so call it per element when structure matters.

Summary

get_text() flattens a tag's text content into one string. Use separator to avoid glued words and strip=True to drop surrounding whitespace; .text is the no-argument shortcut. For clean extracted data, prefer get_text(separator=" ", strip=True) and apply it to the smallest element that still contains the value you want.