TGViewer
Machine Learning with Python Machine Learning with Python @codeprogrammer Β· 68.6K subscribers
Post #4696 7.61K
πŸ—‚ Cheat Sheet on Beautiful Soup 4 (bs4) in Python: HTML/XML Parsing Made Easy and Simple

Beautiful Soup β€” a library for extracting data from HTML and XML files, ideal for web scraping.

πŸ”Ή Installation
pip install beautifulsoup4


πŸ”Ή Import
from bs4 import BeautifulSoup
import requests


πŸ”Ή Basic Parsing
html_doc = "<html><body><p class='text'>Hello, world!</p></body></html>"
soup = BeautifulSoup(html_doc, 'html.parser')  # or 'lxml', 'html5lib'
print(soup.p.text)  # Hello, world!


πŸ”Ή Element Search
# First found element
first_p = soup.find('p')

# Search by class or attribute
text_elem = soup.find('p', class_='text')
text_elem = soup.find('p', {'class': 'text'})

# All elements
all_p = soup.find_all('p')
all_text_class = soup.find_all(class_='text')


πŸ”Ή Working with Attributes and Text
a_tag = soup.find('a')
print(a_tag['href&#39])    # value of the href attribute
print(a_tag.get_text()) # text inside the tag
print(a_tag.text)       # alternative


πŸ”Ή Navigating the Tree
# Moving to parent, children, siblings
parent = soup.p.parent
children = soup.ul.children
next_sibling = soup.p.next_sibling

# Finding the previous/next element
prev_elem = soup.find_previous('p')
next_elem = soup.find_next('div')


πŸ”Ή Parsing a Real Page
response = requests.get('https://example.com')
soup = BeautifulSoup(response.text, 'html. parser')
title = soup.title.text
links = [a['href'] for a in soup.find_all('a', href=True)]


πŸ”Ή CSS Selectors
# More powerful and concise search
items = soup.select('div.content > p.text')
first_item = soup.select_one('a.button')


πŸ’‘ Where it's useful:
🟒 Web scraping and data collection
🟒 Processing HTML/XML reports
🟒 Automating data extraction from websites
🟒 Preparing data for analysis and machine learning


πŸ‘©β€πŸ’» @CodeProgrammer
  • ❀ 21
  • πŸ”₯ 2
  • πŸ‘ 1
More from @codeprogrammer
  1. Oct 9, 2026One of the key moments when I truly understood how transformers work: 🧠✨ "Stop thinking o…
  2. Oct 9, 2026πŸ”– Official PyTorch Tutorials This collection includes: 🫑 PyTorch fundamentals and torch.…
  3. Oct 7, 2026A distinctive bot for subscribing to courses on the most popular educational platforms acr…
  4. Oct 7, 2026Understanding algorithms changes the way you write code. 🧠 This playlist teaches you exac…
  5. Oct 6, 2026πŸ›  Built an AI app with Cursor, Claude Code or Lovable? Publish it on Zibby (zibby.run), a…
  6. Oct 5, 2026πŸš€ ChatGPT Plus & Gemini AI ProπŸ€– ChatGPT Plus β€” 1 Month: $8 ✨ Gemini AI Pro β€” 18 Months:…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook β†’Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 β†’