Получение текста из тега
Есть строка - <p class="text-muted"><span>Артикул:</span>08.01.13</p>, как спарсить только числовую комбинацию "08.01.13" без значения "Актикул"??
Вот полный код:
from bs4 import BeautifulSoup
URL = 'https://t-don.com/catalog/zapchasti-k-selhoztehnike/seyalki/atespar-turciya'
HEADERS = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36', 'accept': '*/*'}
def get_html(url, params=None):
r = requests.get(url, headers=HEADERS, params=params)
return r
def get_content(html):
soup = BeautifulSoup(html, 'html.parser')
items = soup.find_all('div', class_='lst-itm')
parts = []
for item in items:
parts.append({
'title': item.find('a', class_='a-top').get_text(strip=True),
'price': item.find('span', class_='cost-item').get_text(),
'articul': item.find('p', class_='text-muted').get_text(),
})
print(parts)
def parse():
html = get_html(URL)
if html.status_code == 200:
get_content(html.text)
else:
print('Error')
parse()
По строке 'articul': item.find('p', class_='text-muted').get_text() парсится {'title': 'U образный болт M10x175', 'price': '183, 06', 'articul': 'Артикул:08.03.12'}, повторюсь: как исключить "Артикул"?
П.с. вопрос может и туповат, но только начинаю изучение, так что простите.
Ответы (2 шт):
Автор решения: Vadim.Sharoikin
→ Ссылка
можно использовать метод decompose
from bs4 import BeautifulSoup
import requests
URL = 'https://t-don.com/catalog/zapchasti-k-selhoztehnike/seyalki/atespar-turciya'
HEADERS = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36', 'accept': '*/*'}
def get_html(url, params=None):
r = requests.get(url, headers=HEADERS, params=params)
return r
def get_content(html):
soup = BeautifulSoup(html, 'html.parser')
items = soup.find_all('div', class_='lst-itm')
parts = []
for item in items:
item.find('p', class_='text-muted').select_one('span').decompose()
parts.append({
'title': item.find('a', class_='a-top').get_text(strip=True),
'price': item.find('span', class_='cost-item').get_text(),
'articul': item.find('p', class_='text-muted').get_text(),
})
print(parts)
def parse():
html = get_html(URL)
if html.status_code == 200:
get_content(html.text)
else:
print('Error')
parse()
Если элементов больше чем один их надо удалять в цикле
from bs4 import BeautifulSoup
html = """
<p><span class="text-muted">Комплектность: </span><span class="label label-default"></span>Бандаж 1шт</p>
"""
test= BeautifulSoup(html, 'html.parser')
p = test.select_one('p')
for x in p.select('span'):
x.decompose()
print(test)
Автор решения: Евгений Егиоя
→ Ссылка
from bs4 import BeautifulSoup as bs
txt = r'<p class="text-muted"><span>Артикул:</span>08.01.13</p>'
soup = bs(txt, "html.parser")
print(soup.text.split(':')[1])