如何使用python美丽汤只获取级别1的navigableText? [英] How to use python beautiful soup to get only the level 1 navigableText?

查看:20
本文介绍了如何使用python美丽汤只获取级别1的navigableText?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用美丽的汤从这个示例 html 代码中获取文本:

<代码>....<div style="s1"><div style="s2">这里是文本 1</div><div style="s3">这里是文字 2</div>这是文本 3,这就是我想要的.

....

文本 1 和文本 2 处于同一级别 2,文本 3 处于较高级别 1.我只想获取文本 3 并使用此:

 用于 tbody.findAll('div', style="s1") 中的锚点:评论=锚文本印刷评论

但是这些代码让我得到了所有的文本 1、2、3.我如何只获得第一级文本 3?

解决方案

类似:

 用于 tbody.findAll('div', style="s1") 中的锚点:text = ''.join([x for x in anchor.contents if isinstance(x, bs4.element.NavigableString)])

有效.只要知道你也会在那里得到换行符,所以 .strip()ing 可能是必要的.

例如:

 用于 tbody.findAll('div', style="s1") 中的锚点:text = ''.join([x for x in anchor.contents if isinstance(x, bs4.element.NavigableString)])打印([文本])打印([text.strip()])

印刷品

[u'


这是文本 3,这就是我想要的.
'][你'这是文本 3,这就是我想要的.']

(我把它们放在列表中,这样你就可以看到换行符.)

I am using beautiful soup to get the text from this example html code:

....
<div style="s1">
    <div style="s2">Here is text 1</div>
    <div style="s3">Here is text 2</div>
Here is text 3 and this is what I want.
</div>
....

Text 1 and text 2 is at the same level 2 and the text 3 is at the upper level 1. I only want to get the text 3 and used this:

for anchor in tbody.findAll('div', style="s1"):
    review=anchor.text
    print review

But these code get me all the text 1,2,3. How do I only get the first level text 3?

解决方案

Something like:

for anchor in tbody.findAll('div', style="s1"):
    text = ''.join([x for x in anchor.contents if isinstance(x, bs4.element.NavigableString)])

works. Just know that you'll also get the line breaks in there, so .strip()ing might be necessary.

For example:

for anchor in tbody.findAll('div', style="s1"):
    text = ''.join([x for x in anchor.contents if isinstance(x, bs4.element.NavigableString)])
    print([text])
    print([text.strip()])

Prints

[u'


Here is text 3 and this is what I want.
']
[u'Here is text 3 and this is what I want.']

(I put them in lists so you could see the newlines.)

这篇关于如何使用python美丽汤只获取级别1的navigableText?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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