python - 从包含在 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>
.
解决方案
试试下面的代码
result = ''.join([i.strip().replace('"', '') for i in anchor.strings if i.strip()][:-1])
print(result)
输出
'This is a test string'
推荐阅读
- tomcat - TOMCAT - catalina.properties - 自定义变量
- javascript - 删除复杂对象中的元素
- java - 从另一个类创建对象的类调用方法时出现 NullPointerException
- python - 关于 Neo4j + Flask 登录项目的问题
- typescript - 无法将 isoWeekDay 与矩变量一起使用
- python - Pandas 通过检查列表元素是否包含值进行选择
- r - 防止 R 自动获取已安装软件包的最新版本?
- javascript - 是否可以查看 JSON 文件中的多个对象分组?
- python - 如何编写一个递归函数来计算几年后的硬币净值?
- r - Optim() 函数以小数为单位变化?