Как получить текст от <div>с включенным <span>с красивым супом - PullRequest
0 голосов
/ 01 ноября 2018

Это HTML-код

<div class="mxjs-variant-selector mx-variant-selector"
     data-ga-label=""
     name="" >Title <br>
              <span class="mx-price">Price</span>
</div>

Я хочу получить Title и Price в различных переменных

Это мой код

name_box = soup.find('div', attrs={'class': 'mxjs-variant-selector mx-variant-selector'})
title = name_box.text.strip()
name_box1 = soup.find("div", class_="mxjs-variant-selector mx-variant-selector").find("span", class_="mx-price").text
price = name_box1

на заголовке я получаю

Title
(with newline)
Price

по цене, которую я получаю

Price

1 Ответ

0 голосов
/ 02 ноября 2018

Сначала получите текст из элемента span, затем удалите его из супа. Затем вы можете получить title:

from bs4 import BeautifulSoup

html = """<div class="mxjs-variant-selector mx-variant-selector"
     data-ga-label=""
     name="" >Title <br>
              <span class="mx-price">Price</span>
</div>"""

soup = BeautifulSoup(html, "html.parser")

div = soup.find("div", class_="mxjs-variant-selector mx-variant-selector")
price = div.span.text
div.span.extract()
title = div.get_text(strip=True)

print(title)
print(price)

Даю вам:

Title
Price
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...