使用BeautifulSoup获取所选元素旁边的文本

时间:2014-08-26 22:21:12

标签: python beautifulsoup

我有以下HTML:

<div id="foo"><span id="bar">BAR</span> hello</div>

我创建了BeautifulSoup对象:

soup = BeautifulSoup('<div id="foo"><span id="bar">BAR</span> hello</div>')
bar = soup.find(id="bar")

如何使用hello元素获取bar文字?

1 个答案:

答案 0 :(得分:2)

使用next_sibling

>>> from bs4 import BeautifulSoup as bs
>>> data = '<div id="foo"><span id="bar">BAR</span> hello</div>'
>>> soup = bs(data)
>>> bar = soup.find(id="bar")
>>> bar
<span id="bar">BAR</span>
>>> bar.next_sibling.strip()
u'hello'