Найти - Пользователи
Полная версия: Пирсинг HTML не могу забрать текст из тэга
Начало » Python для новичков » Пирсинг HTML не могу забрать текст из тэга
1
mdf
Добрый день!
Парсю HTML страничку и приехал к такой проблеме
Как правильно забрать стоимость (для примера в первом блоке 13 900 000 ₸) она сидит тектом в тэге “P”, но в этм тэге то появляются прочие теги типа div span p.
Кусок кода:
  price = rd.find('p', class_='results-price').text.strip()  
Вот если делаю так, то оно само собой собирается с мусором которые иногда есть а иногда его нет (

Образец куска HTML который обрабатывается:
 <p class="results-price"><div class='info'>Срочно!</div>13 900 000 ₸<span class="append-price"></span> <span class="price-per-meter">/ 408 824 ₸ за м<sup>2</sup></span> </p>
<p class="results-price">16 100 000 ₸<span class="price-per-meter">/ 408 824 ₸ за м<sup>2</sup></span> </p>
mdf
Правильно ли будет - текст во всех тегах с известними классами, а затем исключать этот текст из основного. Или как то иначе можно сделать ?
py.user.next
Надо удалить лишние теги сначала.
https://beautiful-soup-4.readthedocs.io/en/latest/#extract
https://beautiful-soup-4.readthedocs.io/en/latest/#unwrap

  
>>> import bs4
>>> 
>>> text = """<p class="results-price"><div class='info'>Срочно!</div>13 900 000 ₸<span class="append-price"></span> <span class="price-per-meter">/ 408 824 ₸ за м<sup>2</sup></span> </p>"""
>>> soup = bs4.BeautifulSoup(text, 'html.parser')
>>> 
>>> node = soup.find('div', class_='info')
>>> if node:
...     node.extract()
... 
<div class="info">Срочно!</div>
>>> node = soup.find('span', class_='append-price')
>>> if node:
...     node.extract()
... 
<span class="append-price"></span>
>>> node = soup.find('p', class_='results-price')
>>> if node:
...     node.unwrap()
... 
<p class="results-price"></p>
>>> soup
13 900 000  <span class="price-per-meter">/ 408 824  за м<sup>2</sup></span> 
>>> 
>>> text = """<p class="results-price">16 100 000 ₸<span class="price-per-meter">/ 408 824 ₸ за м<sup>2</sup></span> </p>"""
>>> soup = bs4.BeautifulSoup(text, 'html.parser')
>>> 
>>> 
>>> node = soup.find('div', class_='info')
>>> if node:
...     node.extract()
... 
>>> node = soup.find('span', class_='append-price')
>>> if node:
...     node.extract()
... 
>>> node = soup.find('p', class_='results-price')
>>> if node:
...     node.unwrap()
... 
<p class="results-price"></p>
>>> soup
16 100 000 <span class="price-per-meter">/ 408 824  за м<sup>2</sup></span> 
>>>
mdf
py.user.next
>>> node = soup.find('p', class_='results-price')
>>> if node:
… node.unwrap()
Спасибо
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB