仅提取文本,从这个元素,而不是它的孩子们 [英] Only extracting text from this element, not its children
本文介绍了仅提取文本,从这个元素,而不是它的孩子们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想提取只从我的汤最上面的元素中的文本;然而soup.text给所有的子元素的文本:
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:
我
import BeautifulSoup
soup=BeautifulSoup.BeautifulSoup('<html>yes<b>no</b></html>')
print soup.text
输出到这是 YESNO
。我想简单的'是'。
什么是实现这一目标的最佳方式?
What's the best way of achieving this?
修改:我也想是
来输出解析时,&LT; HTML&GT;&LT; B&GT;不&LT ; / b&GT;是&LT; / HTML方式&gt;
Edit: I also want yes
to be output when parsing '<html><b>no</b>yes</html>
'.
推荐答案
怎么样 .find(文= 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'
编辑:
我认为我已经理解你现在想要什么。试试这个:
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屋!
查看全文