【发布时间】:2019-08-12 07:51:24
【问题描述】:
我是 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:
此解决方法对内部嵌套标签无效......
【问题讨论】:
-
那个问题只得到所有标签,但我想以某种方式将文本与其所有可能的标签链接起来......谢谢!
标签: python html beautifulsoup