python - BeautifulSoup 获取字符串的所有标签
问题描述
我是 BeautifulSoup 新手,我想知道是否有任何方法可以通过字符串获取标签。例子:
from bs4 import BeautifulSoup
s = s = "<blockquote><i><b>Quote</b></i></blockquote><br />SOME DESIRED TEXT <h3><i>This is a title</i></h3>"
soup = BeautifulSoup(s, "html.parser")
soup_all = soup.findAll()
for s in soup.strings:
print get_tags_by_string(s)
并获得以下输出get_tags_by_string
:
Quote -> blockquote
Quote -> i
Quote -> b
SOME DESIRED TEXT -> Plain
This is a title -> h3
This is a title -> i
我正在寻找官方文档,但似乎没有功能。
先感谢您!!
编辑:
我已经探索过这种解决方法,但未检测到内部标签......
import bs4
s = "<blockquote><i>Quote</i></blockquote><br />text <h3>This is a title</h3>"
soup = bs4.BeautifulSoup(s, "html.parser")
soup_all = soup.find_all()
for asds in soup.contents:
if isinstance(asds, bs4.element.Tag) and asds.text != "":
print "%s -> %s" % (asds.text, asds.name)
elif isinstance(asds, bs4.element.NavigableString):
print "%s -> None" % asds
输出:
Quote -> blockquote
text -> None
This is a title -> h3
更新:
这个解决方案对我有用:
for content in soup.contents:
if isinstance(content, bs4.element.Tag) and content.text != "":
print "%s -> %s" % (content.text, content.name)
# Nested tags
nested_tags = content.find_all()
for nested_tag in nested_tags:
print "%s -> %s" % (nested_tag.text, nested_tag.name)
elif isinstance(content, bs4.element.NavigableString):
print "%s -> None" % content
输出:
Quote -> blockquote
Quote -> i
Quote -> b
SOME DESIRED TEXT -> Plain
This is a title -> h3
This is a title -> i
您如何看待这种解决方法?可能有效吗?
先感谢您!
更新 2:
此解决方法对内部嵌套标签无效....
解决方案
我相信这就是您可能正在寻找的:
for tag in soup.find_all():
if tag.next_sibling:
if isinstance(tag.next_sibling, bs4.element.Tag):
print("%s -> %s" % (tag.text,tag.name))
else:
print("%s -> %s" % (tag.next_sibling,tag.name))
else:
print("%s -> %s" % (tag.text,tag.name))
输出:
Quote -> blockquote
Quote -> i
Quote -> b
SOME DESIRED TEXT -> br
This is a title -> h3
This is a title -> i
推荐阅读
- python - DirectX 游戏的自动点击程序
- twitter-bootstrap-3 - 即使格式化,Bootstrap3 datetimepicker 也会显示日历?
- python - 试图找到 FP,FN,TP,TN 但我遇到了一些错误
- automation - 我在 MOCHA-Chai 的调用 API 中使用了断言
- asp.net-core - 错误请求,标头太长,错误代码 400(使用 IIS 服务器 .netCore 应用程序运行)
- asp.net-mvc - 将 EditFor 替换为复选框
- python - IMDB 数据集示例上的 Keras 网络错误。不兼容的形状
- git - 如何在 Azure DevOPS 服务器上使用 PAT 克隆 git 存储库
- vue.js - 使用地址查找时vuejs模型不更新
- excel - 如果窗口被锁定,宏不会循环