TGViewer
Python Developer Python Developer @python_tg · 20.9K subscribers
Post #3591 3.88K
📱 Шпаргалка по Beautiful Soup 4

Beautiful Soup — библиотека для извлечения данных из HTML- и XML-файлов, которая отлично подходит для веб-скрапинга.

1. Установка
pip install beautifulsoup4


2. Импорт
from bs4 import BeautifulSoup
import requests


3. Базовый парсинг
html_doc = "<html><body><p class='text'>Привет, мир!</p></body></html>"
soup = BeautifulSoup(html_doc, 'html.parser') # или 'lxml', 'html5lib'
print(soup.p.text) # Привет, мир!


4. Поиск элементов
# Первый найденный элемент
first_p = soup.find('p')

# Поиск по классу или атрибуту
text_elem = soup.find('p', class_='text')
text_elem = soup.find('p', {'class': 'text'})

# Все элементы
all_p = soup.find_all('p')
all_text_class = soup.find_all(class_='text')


5. Работа с атрибутами и текстом
a_tag = soup.find('a')
print(a_tag['href']) # значение атрибута href
print(a_tag.get_text()) # текст внутри тега
print(a_tag.text) # альтернатива


6. Навигация по дереву
# Переход к родителю, детям, соседям
parent = soup.p.parent
children = soup.ul.children
next_sibling = soup.p.next_sibling

# Поиск предыдущего/следующего элемента
prev_elem = soup.find_previous('p')
next_elem = soup.find_next('div')


7. Парсинг реальной страницы
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)]


8. CSS-селекторы
# Более мощный и лаконичный поиск
items = soup.select('div.content > p.text')
first_item = soup.select_one('a.button')


tags: #шпаргалка #полезное

➡ Python Developer | Чат
  • ❤ 7
  • 👍 5
  • 🔥 1
More from @python_tg
  1. Sep 28, 2026📱 Собираем охранника для комнаты на Python и YOLO В статье создают Telegram-бота, который…
  2. Sep 27, 2026▪️ Большая база материалов для изучения Python с нуля Нашли репозиторий, где собраны roadm…
  3. Sep 26, 2026Post #4035
  4. Sep 26, 2026📱 Как работают деструкторы в Python В статье разбирают: 🫡 Как работает __del__; 🫡 Почем…
  5. Sep 25, 2026Post #4032
  6. Sep 25, 2026Лучше безработный, чем вайбкодер ➡ Python Developer | #memes
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 →