【发布时间】:2016-04-04 11:46:42
【问题描述】:
我有一个需要处理的 HTML 文档。我为此使用了'beautifoulsoup'。现在我想从该文档中检索一些“子汤”并将它们加入一个汤中,以便以后可以将其用作需要汤对象的函数的参数。
如果不清楚,我给你举个例子……
from bs4 import BeautifulSoup
my_document = """
<html>
<body>
<h1>Some Heading</h1>
<div id="first">
<p>A paragraph.</p>
<a href="another_doc.html">A link</a>
<p>A paragraph.</p>
</div>
<div id="second">
<p>A paragraph.</p>
<p>A paragraph.</p>
</div>
<div id="third">
<p>A paragraph.</p>
<a href="another_doc.html">A link</a>
<a href="yet_another_doc.html">A link</a>
</div>
<p id="loner">A paragraph.</p>
</body>
</html>
"""
soup = BeautifulSoup(my_document)
# find the needed parts
first = soup.find("div", {"id": "first"})
third = soup.find("div", {"id": "third"})
loner = soup.find("p", {"id": "loner"})
subsoups = [first, third, loner]
# create a new (sub)soup
resulting_soup = do_some_magic(subsoups)
# use it in a function that expects a soup object and calls its methods
function_expecting_a_soup(resulting_soup)
目标是在resulting_soup 中有一个对象,其行为/行为类似于具有以下内容的汤:
<div id="first">
<p>A paragraph.</p>
<a href="another_doc.html">A link</a>
<p>A paragraph.</p>
</div>
<div id="third">
<p>A paragraph.</p>
<a href="another_doc.html">A link</a>
<a href="yet_another_doc.html">A link</a>
</div>
<p id="loner">A paragraph.</p>
有没有方便的方法来做到这一点?如果有比find() 更好的方法来检索“子汤”,我可以改用它。谢谢。
更新
Wondercricket 建议有一个solution,它将包含找到的标签的字符串连接起来,并将它们再次解析成一个新的 BeautifulSoup 对象。虽然这是解决问题的一种可能方法,但重新解析可能需要比我想要的更长的时间,特别是当我想检索其中的大部分并且我需要处理许多此类文档时。 find() 返回 bs4.element.Tag。有没有办法将多个Tags 连接成一个汤而不将Tags 转换为字符串并解析字符串?
【问题讨论】:
标签: python html beautifulsoup html-parsing