使用beautifulsoup以正确的顺序解析项目符号列表

时间:2014-08-28 20:38:49

标签: python beautifulsoup

我正在尝试解析一个网站,其结构与此非常相似:

<div class="InternaTesto">
<p class="MarginTop0">Paragraph 1</p><br>
<p>Paragraph 2</p><br>
<p><strong>Paragraph 3</strong></p><br>
<ul>
    <li style="margin: 0px; text-indent: 0px;"><em>List item 1</em></li>
    <li style="margin: 0px; text-indent: 0px;"><em>List item 2</em></li>
    <li style="margin: 0px; text-indent: 0px;"><em>List item 3</em></li>
    ... Some Other Items ...
</ul>
<p><strong>Paragraph 4</strong></p><br>
<ul>
    <li style="margin: 0px; text-indent: 0px;"><em>List item 1</em></li>
    <li style="margin: 0px; text-indent: 0px;"><em>List item 2</em></li>
    <li style="margin: 0px; text-indent: 0px;"><em>List item 3</em></li>
    ... Some Other Items ...
</ul>
... Some Other paragraphs ...
</div>

我正在尝试提取列表项,并将它们放在正确的段落下。现在我能够找到列表项,但它的顺序不正确。这是我正在使用的代码:

textOfTheArticle=[] 

for p in rawArticleData.find('div', attrs={'class':'InternaTesto'}).find_all("p"):
    textOfTheArticle.append(p.get_text())
    print(p.get_text() + "\n")

有没有办法用所有<li>项创建子列表或单独的列表?

1 个答案:

答案 0 :(得分:1)

您可以找到所有段落,每个段落都可以获得第3个下一个兄弟:

from bs4 import BeautifulSoup

data = """
Your html here
"""

soup = BeautifulSoup(data)
for p in soup.find('div', attrs={'class':'InternaTesto'}).find_all("p"):
    print p.text, [li.text for li in list(p.next_siblings)[2].find_all('li')]

打印:

Paragraph 1 []
Paragraph 2 []
Paragraph 3 [u'List item 1', u'List item 2', u'List item 3']
Paragraph 4 [u'List item 1', u'List item 2', u'List item 3']

更可靠的方法是迭代每个段落的下一个兄弟,直到我们点击下一个段落标记:

soup = BeautifulSoup(data)
for p in soup.find('div', attrs={'class':'InternaTesto'}).find_all("p"):
    print p.text
    for sibling in p.next_siblings:
        if sibling.name == 'ul':
            print [li.text for li in sibling.find_all('li')]
        if sibling.name == 'p':
            break

希望有所帮助。