Как извлечь весь текст под определенным заголовком? В этом случае мне нужно извлечь текст из темы 2. РЕДАКТИРОВАТЬ: На других веб-страницах «Тема 2» иногда отображается как третий или первый заголовок. «Тема 2» не всегда находится в одном и том же месте и не всегда имеет один и тот же идентификационный номер.
# import library
from bs4 import BeautifulSoup
# dummy webpage text
body = '''
Topic 1
This is the first sentence.
This is the second sentence.
This is the third sentence.
Topic 2
This is the fourth sentence.
This is the fifth sentence.
Topic 3
This is the sixth sentence.
This is the seventh sentence.
This is the eighth sentence.
'''
# convert text to soup
soup = BeautifulSoup(body, 'lxml')
Если я извлеку текст только из «Темы 2», мой результат будет таким.
This is the fourth sentence. This is the fifth sentence.
Мои попытки решить эту проблему:
Я попробовал суп.select( 'h2 + p'), но это позволило мне получить только первые предложения под каждым заголовком.
[
This is the first sentence.
,
This is the fourth sentence.
,
This is the sixth sentence.
]
Я тоже пробовал это, но мне выдавался весь текст, хотя мне нужен только текст по теме 2:
import pandas as pd
lst = []
for row in soup.find_all('p'):
text_dict = {}
text_dict['text'] = row.text
lst.append(text_dict)
df = pd.DataFrame(lst)
df
| | text |
|---|-------------------------------|
| 0 | This is the first sentence. |
| 1 | This is the second sentence. |
| 2 | This is the third sentence. |
| 3 | This is the fourth sentence. |
| 4 | This is the fifth sentence. |
| 5 | This is the sixth sentence. |
| 6 | This is the seventh sentence. |
| 7 | This is the eighth sentence. |
Подробнее здесь: https://stackoverflow.com/questions/603 ... fic-header