BeautifulSoup: Найти все содержимое в теге <p>между двумя тегами <h2> - PullRequest
0 голосов
/ 16 апреля 2020

У меня есть веб-страница для анализа, источник следующий:

<div class=WordSection1>

<p class=MsoTitle><a name="_nvfbzzqeywr7"></a><span lang=EN>Geometry</span></p>
<h2><a name="_99n9742wmg4y"></a><span lang=EN>Algebraic Geometry </span></h2>

<p class=MsoNormal><span lang=EN>It is a type of geometry which deals with
zeros of multivariate polynomial. It consists of linear and polynomial
algebraic equations used to solve the sets of zeros. The uses of this type <span
class=GramE>consists</span> of Cryptography, String theory, etc.</span></p>

<h2><a name="_64xtqrllvykm"></a><span lang=EN>Discrete Geometry</span></h2>

<p class=MsoNormal><span lang=EN>It is a type of Geometry, mainly concerned
with the relative position of simple geometric objects, such as points, lines,
Triangles, Circles, etc.</span></p>

<h2><a name="_mdul98ybu9wv"></a><span lang=EN>Differential Geometry</span></h2>

<p class=MsoNormal><span lang=EN>It uses techniques of algebra and calculus for
problem solving. The different problem involves general relativity in physics <span
class=SpellE><span class=GramE>etc</span></span><span class=GramE>,.</span></span></p>

</div>

Я хочу проанализировать данные внутри в виде списка и соответствующий тег в другом списке, чтобы я мог отобразить его позже в форма python словаря. Мне даже приходится игнорировать другие теги, такие как h1 и h3.

Ожидаемые результаты:

headers = ['Algebraic Geometry','Discrete Geometry','Differential Geometry']
content = ['It is a type of geometry which deals with
zeros of multivariate polynomial. It consists of linear and polynomial
algebraic equations used to solve the sets of zeros. The uses of this type consists of Cryptography, String theory, etc.','It is a type of Geometry, mainly concerned
with the relative position of simple geometric objects, such as points, lines,
Triangles, Circles, etc.','It uses techniques of algebra and calculus for
problem solving. The different problem involves general relativity in physics etc,.']

Я могу получить все заголовки. Но для получения

теги внутри заголовков, я не могу получить результаты. Вот что я попробовал:

content = []

# find the node with id of "WordSection1"
mark = soup.find_all(class_="WordSection1")
print(mark)

# walk through the siblings of the parent (H2) node 
# until we reach the next H2 node
for elt in mark.parent.nextSiblingGenerator():
    if elt.name == "h2":
        break
    if hasattr(elt, "text"):
        content.append(elt.text)

Пожалуйста, помогите мне в этом.

Ответы [ 3 ]

0 голосов
/ 16 апреля 2020

Я попытался express это на Web Scraping Language с использованием Xpath

GOTO targeturl.com
EXTRACT {'header': '//h2/preceding-sibling::p[@class="MsoNormal"]', 
         'desc': '//p[@class="MsoNormal"]/following-sibling::h2'}

Это должно привести к массиву заголовков и описаний. Однако, поскольку ни одно из двух полей не содержится в родительском элементе, если в одной из записей отсутствует описание, вы не получите однозначного соответствия.

0 голосов
/ 16 апреля 2020

Другое решение. Если мы просто последуем вашему примеру кода, ответ FireM будет правильным. Вы должны опубликовать всю структуру HTML.

from simplified_scrapy import SimplifiedDoc,req,utils
html = 'your html'
doc = SimplifiedDoc(html)
h2s = doc.selects('div.WordSection1>h2')
ps = h2s.next.text
h2s = h2s.text
print (h2s)
print (ps)

Результат:

['Algebraic Geometry', 'Discrete Geometry', 'Differential Geometry']
['It is a type of geometry which deals with zeros of multivariate polynomial. It consists of linear and polynomial algebraic equations used to solve the sets of zeros. The uses of this type consists of Cryptography, String theory, etc.', 'It is a type of Geometry, mainly concerned with the relative position of simple geometric objects, such as points, lines, Triangles, Circles, etc.', 'It uses techniques of algebra and calculus for problem solving. The different problem involves general relativity in physics etc,.']
0 голосов
/ 16 апреля 2020

Это должно делать то, что вам нужно

# read html code snippet
soup = BeautifulSoup(html, 'html.parser')

# find the node with id of "WordSection1"
mark = soup.find(class_="WordSection1")

# initialize container objects
headers = []
content = []

# get all h2 and p(with class MsoNormal) tags
find_headers = mark.find_all_next('h2')
find_content = mark.find_all_next('p', {'class': 'MsoNormal'})

# get text of tags
for head, cont in zip(find_headers, find_content):
   headers.append(head.text)
   content.append(cont.text)

# output lists
print(f"Headers = {headers} '\n\nContent = {content}")```
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...