【问题标题】:How to select only this text node using BeautifulSoup and Python?如何使用 BeautifulSoup 和 Python 仅选择此文本节点?
【发布时间】:2015-10-21 14:29:09
【问题描述】:

我有这个 html 结构:

<div class="foo">
    <h3>Title</h3>
    <br>Some text I want to retrieve. <br><br> This text too.
    <br> (numbers and position of "br" tag indetermined) And this one too.
    <div class="subfoo">Some other text I don't want.</div>
</div>

在我的python脚本中,我写了:

exampleSoup = bs4.BeautifulSoup(res.text, "html.parser")
elems = exampleSoup.select('.foo')
print(elems[0].getText())

不出所料,我得到了全文:

Title
Some text I want to retrieve.
Some other text I don't want.

如何仅获取 div 中没有标签的字符串,即:“我想检索一些文本。这个文本也是。还有这个。”? 感谢您的帮助。

【问题讨论】:

标签: python beautifulsoup data-extraction


【解决方案1】:

您可以使用.next_sibling 获取树中的下一个元素。

示例

>>> soup = BeautifulSoup(html)
>>> print soup.prettify()
<html>
 <body>
  <div class="foo">
   <h3>
    Title
   </h3>
   Some text I want to retrieve.
   <div class="subfoo">
    Some other text I don't want.
   </div>
  </div>
 </body>
</html>

>>> print soup.find('div', { 'class' : 'foo' } ).h3.next_sibling.strip()
Some text I want to retrieve.

【讨论】:

  • 感谢您的回答!它返回给我&lt;br&gt;。确实,很抱歉,但我忘了提到与文本一起随机放置的一些
    。我已经更新了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-22
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多