Удаление лишнего элемента для парсера
Есть парсер, считывает цену, но немного некорректно, причиной тому является странная верстка сайта: 
Я все данные записываю в список:
def get_content(html):
soup = BeautifulSoup(html,'html.parser')
items = soup.find_all('div', class_ = 'b-catalog__item')
cards = []
for item in items:
cards.append(
{
'title' : item.find('div', class_='b-catalog__item-title-wrap').get_text(strip = True),
'link_product': HOST + item.find('div', class_='b-catalog__item-title-wrap').find('a').get('href'),
'img': HOST + item.find('div', class_='b-catalog__item-wrap').find('a').get('href'),
'price' : item.find('div', class_='b-catalog__item-price').get_text(strip = True)
}
)
return cards
если же поменяю
'price' : item.find('div', class_='b-catalog__item-price').get_text(strip = True)
на
'price' : item.find('span', class_='b-price__num').get_text(strip = True)
То особо ничего не поменяется
Суть в том, два варианта:
- Игнорирование копеек, не знаю, как это реализовать
- Либо же Сделать разделение копеек, но так, чтобы записывалось в одну колонку файла
Ответы (1 шт):
Автор решения: gil9red
→ Ссылка
Можно через метод decompose удалить тег sup.
Пример:
from bs4 import BeautifulSoup
item = BeautifulSoup("""\
<span class="b-price__num">
32
<sup class="sup_cop">59</sup>
<span>
""", "html.parser")
price_el = item.find('span', class_='b-price__num')
price_el.select_one('.sup_cop').decompose()
print(price_el.get_text(strip=True))
# 32
Использование в коде из вопроса:
...
for item in items:
title_el = item.find('div', class_='b-catalog__item-title-wrap')
price_el = item.find('span', class_='b-price__num')
price_el.select_one('.sup_cop').decompose() # Удаление копеек
cards.append({
'title' : title_el.get_text(strip=True),
'link_product': HOST + title_el.find('a').get('href'),
'img': HOST + item.find('div', class_='b-catalog__item-wrap').find('a').get('href'),
'price' : price_el.get_text(strip=True),
})
return cards