仅从此元素中提取文本,而不是其子元素 [英] Only extracting text from this element, not its children

查看:28
本文介绍了仅从此元素中提取文本,而不是其子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想从汤的最顶层元素中提取文本;然而,soup.text 也给出了所有子元素的文本:

我有

导入 BeautifulSoup汤=BeautifulSoup.BeautifulSoup('<html>是<b>否</b></html>')打印汤.text

对此的输出是yesno.我只想说是".

实现这一目标的最佳方法是什么?

编辑:我也希望在解析 'no</b>yes</html> 时输出 yes'.

解决方案

.find(text=True) 怎么样?

<预><代码>>>>BeautifulSoup.BeautifulSOAP('<html>yes<b>no</b></html>').find(text=True)你是的>>>BeautifulSoup.BeautifulSOAP('<html><b>no</b>yes</html>').find(text=True)你不

我想我现在明白你想要什么了.试试这个:

<预><代码>>>>BeautifulSoup.BeautifulSOAP('<html><b>no</b>yes</html>').html.find(text=True, recursive=False)你是的>>>BeautifulSoup.BeautifulSOAP('<html>yes<b>no</b></html>').html.find(text=True, recursive=False)你是的

I want to extract only the text from the top-most element of my soup; however soup.text gives the text of all the child elements as well:

I have

import BeautifulSoup
soup=BeautifulSoup.BeautifulSoup('<html>yes<b>no</b></html>')
print soup.text

The output to this is yesno. I want simply 'yes'.

What's the best way of achieving this?

Edit: I also want yes to be output when parsing '<html><b>no</b>yes</html>'.

解决方案

what about .find(text=True)?

>>> BeautifulSoup.BeautifulSOAP('<html>yes<b>no</b></html>').find(text=True)
u'yes'
>>> BeautifulSoup.BeautifulSOAP('<html><b>no</b>yes</html>').find(text=True)
u'no'

EDIT:

I think that I've understood what you want now. Try this:

>>> BeautifulSoup.BeautifulSOAP('<html><b>no</b>yes</html>').html.find(text=True, recursive=False)
u'yes'
>>> BeautifulSoup.BeautifulSOAP('<html>yes<b>no</b></html>').html.find(text=True, recursive=False)
u'yes'

这篇关于仅从此元素中提取文本,而不是其子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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