查找HTML第一层级中的所有文本使用美丽的汤 - 的Python [英] Find All text within 1 level in HTML using Beautiful Soup - Python

查看:162
本文介绍了查找HTML第一层级中的所有文本使用美丽的汤 - 的Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用美丽的汤完成以下

示例HTML

 < D​​IV ID =DIV1>
 文本1
 < D​​IV ID =DIV2>
   文本2
   < D​​IV ID =DIV3>
    文本3
   < / DIV>
 < / DIV>
< / DIV>

我需要在这做一个搜索,返回到我的列表

的不同实例

文本1
文本2
文本3

我试图做一个的findAll('DIV'),但它重复同样的文本多次,即它会返回

文本1文本2文本3
文本2文本3
文本3


解决方案

那么,你的问题是,的.text 还包括所有子节点的文本。你必须手动得到只有那些文本节点是直接的节点的孩子。另外,有可能是一个给定的一个内的多个文本节点,例如:

 < D​​IV>
    你好
        < D​​IV>
            FOOBAR
        < / DIV>
    世界!
< / DIV>

你怎么希望他们要连接?下面是用空格加入他们的函数:

 高清extract_text(节点):
    回报'。加入(在节点在t t.strip()(文= TRUE,递归= FALSE))

通过我的例子:

 在[27]:T =
< D​​IV>
    你好
        < D​​IV>
            FOOBAR
        < / DIV>
    世界!
< / DIV>中,在[28]:汤= BeautifulSoup(T)在[29]:图(extract_text,汤('格'))
出[29]:[!u'Hello世界,u'foobar']

和你的例子:

 在[32]:T =
< D​​IV ID =DIV1>
 文本1
 < D​​IV ID =DIV2>
   文本2
   < D​​IV ID =DIV3>
    文本3
   < / DIV>
 < / DIV>
< / DIV>中,在[33]:汤= BeautifulSoup(T)在[34]:图(extract_text,汤('格'))
出[34]:[u'Text1',u'Text2',u'Text3']

I need to use beautiful soup to accomplish the following

Example HTML

<div id = "div1">
 Text1
 <div id="div2>
   Text2
   <div id="div3">
    Text3
   </div>
 </div>
</div>

I need to do a search over this to return to me in separate instances of a list

Text1
Text2
Text3

I tried doing a findAll('div'), but it repeated the same Text multiple times ie it would return

Text1 Text2 Text3
Text2 Text3
Text3

解决方案

Well, you problem is that .text also includes text from all the child nodes. You'll have to manually get only those text nodes that are immediate children of a node. Also, there might be multiple text nodes inside a given one, for example:

<div>
    Hello
        <div>
            foobar
        </div>
    world!
</div>

How do you want them to be concatenated? Here is a function that joins them with a space:

def extract_text(node):
    return ' '.join(t.strip() for t in node(text=True, recursive=False))

With my example:

In [27]: t = """
<div>
    Hello
        <div>
            foobar
        </div>
    world!
</div>"""

In [28]: soup = BeautifulSoup(t)

In [29]: map(extract_text, soup('div'))
Out[29]: [u'Hello world!', u'foobar']

And your example:

In [32]: t = """
<div id = "div1">
 Text1
 <div id="div2">
   Text2
   <div id="div3">
    Text3
   </div>
 </div>
</div>"""

In [33]: soup = BeautifulSoup(t)

In [34]: map(extract_text, soup('div'))
Out[34]: [u'Text1 ', u'Text2 ', u'Text3']

这篇关于查找HTML第一层级中的所有文本使用美丽的汤 - 的Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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