Я новичок в 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
Я смотрю официальный документ, но, похоже, для этого нет функциональности.
Заранее спасибо !!
EDIT:
Я исследовал этот обходной путь, но внутренние теги не обнаружены ...
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
UPDATE:
Это решение работает для меня:
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:
Этот обходной путь недопустим для внутренних вложенных тегов ....