Searching by Text Inside a Tag
You can search for tags whose text content matches a string, a regular expression, or a function. The filter argument is string (aliased as text) and it matches the text inside the tag, not the tag's attributes.
Exact or Partial Text
from bs4 import BeautifulSoup
html = "<div><span>Hello world</span><p>Hi there</p></div>"
soup = BeautifulSoup(html, "html.parser")
print(soup.find(string="Hello world").parent) # <span>Hello world</span>
print(soup.find(text="Hello world")) # the NavigableString itself
print(soup.find_all(text="Hi")) # matches <p>Hi there</p>'s text
By default the match is case-insensitive and partial; pass a function or regex for exactness.
Regular Expressions
import re
html = "<p>Price: $9.99</p><p>Ship: free</p>"
soup = BeautifulSoup(html, "html.parser")
prices = soup.find_all(string=re.compile(r"\$\d+\.\d{2}"))
print([str(p) for p in prices]) # ['$9.99']
Function Filters on Text
def is_short(s):
return len(s.strip()) < 5
print(soup.find_all(string=is_short))
Case Sensitivity
For case-sensitive or exact matching, use a compiled regex with the re.IGNORECASE flag only when you want case-insensitive, or a function:
print(soup.find_all(string=re.compile("hi", re.IGNORECASE)))
print(soup.find_all(text=lambda t: t and t.strip().lower() == "hi there"))
Summary
The string/text filter searches tags by their text content with exact strings, compiled regexes, or functions. Use it to locate labels, prices, and headings by what they say rather than how they are tagged, and combine it with .parent or .get_text() to pull the value you actually need.