首页 > 解决方案 > 从包含在 HTML 标记和不带标记的字符串中的一系列字符串中提取文本

问题描述

考虑以下 HTML:

<li>
  <a href="url">
    <b>This</b>
    " is "
    <b>a</b>
    " test "
    <b>string</b>
    "!"
  </a>
</li>

我想提取<a>标签之间的所有文本,除了"!". 换句话说,包含在第一个开头<b>和最后一个结尾之间的文本</b>: This is a test string

from bs4 import BeautifulSoup

html = '''
<li>
<a href="url">
<b>This</b>
" is "
<b>a</b>
" test "
<b>string</b>
"!"
</a>
</li>
'''
soup = BeautifulSoup(html)
anchor = soup.a

请注意,<b>没有标签的标签和字符串的数量会有所不同,next或者next_sibling不起作用。

有没有更简单的方法来做到这一点?

编辑: 理想情况下,我想要一种方法,即使我在最后一个</b>.

标签: pythonpython-3.xbeautifulsoup

解决方案


试试下面的代码

result = ''.join([i.strip().replace('"', '') for i in anchor.strings if i.strip()][:-1])
print(result)

输出

'This is a test string'

推荐阅读