BeautifulSoup获取所有字符串标签

时间:2019-03-21 12:44:59

标签: python html 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:

此解决方法不适用于内部嵌套标签。...

2 个答案:

答案 0 :(得分:0)

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

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))

答案 1 :(得分:0)

我相信这就是您要寻找的东西:

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