L
L
LeakySpoon2022-03-11 18:29:14
Python
LeakySpoon, 2022-03-11 18:29:14

How to parse text from a tag at the same level as the desired one?

There is something like this:

<div>
    <p class="1">
    <label>"Значение, которое нужно спарсить"</label>
</div>
<div>
    <p class="2">
    <label>"Значение, которое мне не нужно"</label>
</div>

How do I know the class p to pull out only the value that is on the same level with it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Kadabrov, 2022-03-11
@Kadabrov

soup.find('p',  class_='1').find('label').getText()

A
AVKor, 2022-03-12
@AVKor

from bs4 import BeautifulSoup

DOC = '''
<html>
<body>
<div>
    <p class="1">
    <label>Значение, которое нужно спарсить</label>
</div>
<div>
    <p class="2">
    <label>Значение, которое мне не нужно</label>
</div>
<div>
    <p class="1">
    <label>Ещё одно значение, которое нужно спарсить</label>
</div>
</body>
</html>
'''

soup = BeautifulSoup(DOC, 'lxml')

for par in soup.find_all('p', class_='1'):
    label = par.find_parent('div').find('label')
    print(label.text)

N
nk_nkt, 2022-03-12
@nk_nkt

lst = [tag_p.get_text() for tag_p in soup.select(".1")]
# take what you need from the list

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question