Как я могу вставить новый тег в объект BeautifulSoup?
Пытаюсь разобраться в конструкции HTML с BS.
Я пытаюсь вставить новый тег:
self.new_soup.body.insert(3, """<div id="file_history"></div>""")
когда я проверяю результат, я получаю:
<div id="file_histor"y></div>
Поэтому я вставляю очищаемую строку для веб-браузера html.
То, что я ожидаю увидеть это:
<div id="file_history"></div>
Как мне вставить новый div
пометить в позиции 3 с идентификатором file_history
?
4 ответа
Решение
Используйте фабричный метод для создания новых элементов:
new_tag = self.new_soup.new_tag('div', id='file_history')
и вставьте это:
self.new_soup.body.insert(3, new_tag)
Смотрите документацию о том, как добавить тег:
soup = BeautifulSoup("<b></b>")
original_tag = soup.b
new_tag = soup.new_tag("a", href="http://www.example.com")
original_tag.append(new_tag)
original_tag
# <b><a href="http://www.example.com"></a></b>
new_tag.string = "Link text."
original_tag
# <b><a href="http://www.example.com">Link text.</a></b>
Другие ответы прямо из документации. Вот ярлык:
from bs4 import BeautifulSoup
temp_soup = BeautifulSoup('<div id="file_history"></div>')
# BeautifulSoup automatically add <html> and <body> tags
# There is only one 'div' tag, so it's the only member in the 'contents' list
div_tag = temp_soup.html.body.contents[0]
# Or more simply
div_tag = temp_soup.html.body.div
your_new_soup.body.insert(3, div_tag)
Пример того, как это сделать внутри определенной области тегов, например<head>
Хорошие ответы здесь привели меня к документации, чтобы узнать больше о том, как удовлетворить мои конкретные потребности.
Я надеюсь, что этот пример поможет некоторым другим, кто задаст этот вопрос/ответ, увидеть более широкую картину.
from bs4 import BeautifulSoup
orig_html = """<html>
<head></head>
<body><h1>Some Body</h1></body>
</html>
"""
orig_soup = BeautifulSoup(orig_html, "html5lib")
# Find <head> area first
head = orig_soup.find("head")
# Just showing that my <head> initially had NO content
print("Head Contents:")
print(f'"{head.contents}"')
print()
# Append content to <head> using the soup.new_tag method
new_style_tag = orig_soup.new_tag(
"link", href="style.css", rel="stylesheet", type="text/css"
)
head.append(new_style_tag)
# Verify that <head> now as the new contents
print("Head Contents:")
print(f'"{head.contents}"')
print()
new_html_text = orig_soup.prettify()
# Check how it appears in the HTML
print(new_html_text)
А вот результат работы приведенного выше скрипта.
Head Contents:
"[]"
Head Contents:
"[<link href="style.css" rel="stylesheet" type="text/css"/>]"
<html>
<head>
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body><h1>Some Body</h1></body>
</html>