我只想提取汤中最上面的元素的文本; 然而 soup.text 也提供了所有子元素的文本:
是的
import BeautifulSoup soup=BeautifulSoup.BeautifulSoup('<html>yes<b>no</b></html>') print soup.text
输出是 yesno,我只需要“ yes”。
yesno
实现这一目标的最佳方法是什么?
编辑 : 我还希望在解析‘ <html><b>no</b>yes</html>’时输出 yes。
<html><b>no</b>yes</html>
yes
You could use contents
>>> print soup.html.contents[0] yes
or to get all the texts under html, use findAll(text=True, recursive=False)
findAll(text=True, recursive=False)
>>> soup = BeautifulSoup.BeautifulSOAP('<html>x<b>no</b>yes</html>') >>> soup.html.findAll(text=True, recursive=False) [u'x', u'yes']
above joined to form a single string
>>> ''.join(soup.html.findAll(text=True, recursive=False)) u'xyes'
what about .find(text=True)?
.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'
You might want to look into lxml's soupparser module, which has support for XPath:
>>> from lxml.html.soupparser import fromstring >>> s1 = '<html>yes<b>no</b></html>' >>> s2 = '<html><b>no</b>yes</html>' >>> soup1 = fromstring(s1) >>> soup2 = fromstring(s2) >>> soup1.xpath("text()") ['yes'] >>> soup2.xpath("text()") ['yes']
This works for me in bs4:
import bs4 node = bs4.BeautifulSoup('<html><div>A<span>B</span>C</div></html>').find('div') print "".join([t for t in node.contents if type(t)==bs4.element.NavigableString])
output:
AC