【问题标题】:BeautifulSoup get all tags of stringsBeautifulSoup 获取字符串的所有标签
【发布时间】: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


【解决方案1】:

根据您的评论,我编辑了代码:

from bs4 import BeautifulSoup
s = "<blockquote><i>Quote</i></blockquote><br />text <h3>This is a title</h3>"
soup = BeautifulSoup(s, "html.parser")

for tag in soup.find_all():
    print("%s -> %s" % (tag.text, tag.name))

输出:

Quote -> blockquote
Quote -> i
 -> br
This is a title -> h3

注意:br 也被检测为标签。如果你想避免打印 br 标签,你可以在打印之前添加一个 if 语句,如下所示:

for tag in soup.find_all():
    if tag.text != "":
         print("%s -> %s" % (tag.text, tag.name))

【讨论】:

  • 是的,我也有这种解决方法,但是这种方法不能识别“文本”字符串值,所以它对我无效...:/
  • “文本”字符串值是什么意思?它生成预期的输出。它打印所有标签和其中的文本
  • 如果您仔细观察,您会看到一个未以这种方式处理的“某些文本要求”
【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 2011-05-30
    • 2019-10-30
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 2015-06-27
    相关资源
    最近更新 更多