使用beautifulsoup查找下一个兄弟姐妹直到某个兄弟姐妹 [英] Find next siblings until a certain one using beautifulsoup

查看:30
本文介绍了使用beautifulsoup查找下一个兄弟姐妹直到某个兄弟姐妹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

网页是这样的:

section1

<p>文章</p><p>文章</p><p>文章</p><h2>section2</h2><p>文章</p><p>文章</p><p>文章</p>

如何找到包含文章的每个部分?即找到h2后,找到nextsiblings

直到下一个h2.

如果网页是这样的:(通常是这种情况)

<h2>section1</h2><p>文章</p><p>文章</p><p>文章</p>

<div><h2>section2</h2><p>文章</p><p>文章</p><p>文章</p>

我可以编写如下代码:

 用于soup.findAll('div') 中的部分:...在 section.findAll('p') 中发布

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

解决方案

我认为你可以这样做:

 用于soup.findAll('h2') 中的部分:nextNode = 节而真:nextNode = nextNode.nextSibling尝试:tag_name = nextNode.name除了属性错误:标签名称 = ""如果 tag_name == "p":打印 nextNode.string别的:打印 "*****"休息

给定:

section1

<p>文章1</p><p>文章2</p><p>文章3</p><h2>section2</h2><p>文章4</p><p>文章5</p><p>文章6</p>

输出:

article1第2条第三条*****第四条第五条第六条*****

The webpage is something like this:

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

<h2>section2</h2>
<p>article</p>
<p>article</p>
<p>article</p>

How can I find each section with articles within them? That is, after finding h2, find nextsiblings

until the next h2.

If the webpage were like: (which is normally the case)

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

<div>
<h2>section2</h2>
<p>article</p>
<p>article</p>
<p>article</p>
</div>

I can write codes like:

for section in soup.findAll('div'):
...
    for post in section.findAll('p')

But what should I do with the first webpage if I want to get the same result?

解决方案

I think you can do something like this:

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

Given:

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

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

Output:

article1
article2
article3
*****
article4
article5
article6
*****

这篇关于使用beautifulsoup查找下一个兄弟姐妹直到某个兄弟姐妹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆