首页 > 解决方案 > 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:

此解决方法对内部嵌套标签无效....

标签: pythonhtmlbeautifulsoup

解决方案


我相信这就是您可能正在寻找的:

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

推荐阅读