Skip to content

STRING SEARCHING - Finding by text content

Python
#!/usr/bin/env python3
"""STRING SEARCHING - Finding by text content"""
from bs4 import BeautifulSoup
import re
html = """
<html><body>
<p>Hello World</p>
<p>Goodbye World</p>
<div>Hello Universe</div>
<span>World Peace</span>
</body></html>
"""
soup = BeautifulSoup(html, 'html.parser')
print("String Searching:")
hello_tags = soup.find_all(string=re.compile('Hello'))
print(f"  Contains 'Hello': {hello_tags}")
world_tags = soup.find_all(string=re.compile('World'))
print(f"  Contains 'World': {world_tags}")
exact = soup.find(string='Hello World')
print(f"  Exact match: {exact}")