Python 使用beautifulsoup查找下一个兄弟姐妹,直到某个兄弟姐妹

Python 使用beautifulsoup查找下一个兄弟姐妹,直到某个兄弟姐妹,python,find,beautifulsoup,scrape,siblings,Python,Find,Beautifulsoup,Scrape,Siblings,该网页如下所示: <h2>section1</h2> <p>article</p> <p>article</p> <p>article</p> <h2>section2</h2> <p>article</p> <p>article</p> <p>article</p> for section in so

该网页如下所示:

<h2>section1</h2>
<p>article</p>
<p>article</p>
<p>article</p>

<h2>section2</h2>
<p>article</p>
<p>article</p>
<p>article</p>
for section in soup.findAll('h2'):
    nextNode = section
    while True:
        nextNode = nextNode.nextSibling
        try:
            tag_name = nextNode.name
        except AttributeError:
            tag_name = ""
        if tag_name == "p":
            print nextNode.string
        else:
            print "*****"
            break

但是如果我想得到同样的结果,我应该如何处理第一个网页呢?

我想你可以这样做:

<h2>section1</h2>
<p>article</p>
<p>article</p>
<p>article</p>

<h2>section2</h2>
<p>article</p>
<p>article</p>
<p>article</p>
for section in soup.findAll('h2'):
    nextNode = section
    while True:
        nextNode = nextNode.nextSibling
        try:
            tag_name = nextNode.name
        except AttributeError:
            tag_name = ""
        if tag_name == "p":
            print nextNode.string
        else:
            print "*****"
            break
鉴于:

<h2>section1</h2>
<p>article1</p>
<p>article2</p>
<p>article3</p>

<h2>section2</h2>
<p>article4</p>
<p>article5</p>
<p>article6</p>

下一个迭代器在这里也很有用:

for i in soup.find_all('h2'):
    for sib in i.next_siblings:
        if sib.name == 'p':
            print(sib.text)
        elif sib.name == 'h2':
            print ("*****")
            break

非常感谢。这确实是一个独立的章节,但似乎并没有使文章属于某个章节。我希望得到与我给出的第一个示例相同的结果。@user1550725请再次检查解决方案。我认为这个解决方案是根据文章的章节来划分文章的。我实际上是在用Calibre来制作一个我想下载的网页。这涉及到识别章节和章节内的文章(之后将其转换为电子书)。您给出的解决方案似乎将节名和文章视为相同的。@user1550725“soup.findAll('h2')”将为您提供与文章不同的所有节。而“section.nextSibling”将为您提供nextNode,您将检查它是文章(具有标记)还是节。我假设结构与您提供的相同(仅表示和)。你得到的章节和文章,由你自己决定,是否相同或分开处理。我希望这能澄清你的困惑。这是维基百科页面吗?
for i in soup.find_all('h2'):
    for sib in i.next_siblings:
        if sib.name == 'p':
            print(sib.text)
        elif sib.name == 'h2':
            print ("*****")
            break