Парсер Python3 выборка тегов
имею такую структура сайта:
<div class="wrapper">
<div class="menu">
<ul>
<li><a href="index.php" class="active">Главная</a></li>
<li><a href="news.php">Новости</a></li>
<li><a href="contacts.php">Контакты</a></li>
<li><a href="company.php">О компании</a></li>
<li><a href="map.php">Как добраться</a></li>
</ul>
</div>
</div>
И такой код в python
with open("project.html", encoding='utf-8') as file:
src = file.read()
soup = BeautifulSoup(src, "lxml")
wrapper = soup.find_all("div", class_="wrapper")
for item in wrapper:
head = item.find("div", class_="menu").find("li")
print(head)
get_data("http://old.code.mu/exercises/advanced/php/parsing/poetapnyj-parsing-i-metod-pauka/1/index.php")
как сделать так, чтобы он выводил все теги li, find_all не подходит.
Ответы (1 шт):
Автор решения: Jack_oS
→ Ссылка
import requests
from bs4 import BeautifulSoup
html = '<div class="wrapper"><div class="menu"><ul><li><a href="index.php" class="active">Главная</a></li><li><a href="news.php">Новости</a></li><li><a href="contacts.php">Контакты</a></li><li><a href="company.php">О компании</a></li><li><a href="map.php">Как добраться</a></li></ul></div></div>'
soup = BeautifulSoup(html, 'html.parser')
rows = soup.find_all('li')
for r in rows:
print(r)
выведет список всех <li>:
<li><a class="active" href="index.php">Главная</a></li>
<li><a href="news.php">Новости</a></li>
<li><a href="contacts.php">Контакты</a></li>
<li><a href="company.php">О компании</a></li>
<li><a href="map.php">Как добраться</a></li>
а если так:
for r in rows:
print(f"{r.find('a')['href']:15} {r.find('a').text}")
то выведет хвост ссылки и название раздела:
index.php Главная
news.php Новости
contacts.php Контакты
company.php О компании
map.php Как добраться