【发布时间】:2016-05-15 04:24:58
【问题描述】:
我试图注释掉我稍后想要的 HTML 页面的一部分,而不是使用漂亮的汤 tag.extract() 函数来提取它。例如:
<h1> Name of Article </h2>
<p>First Paragraph I want</p>
<p>More Html I'm interested in</p>
<h2> Subheading in the article I also want </h2>
<p>Even more Html i want blah blah blah</p>
<h2> References </h2>
<p>Html I want commented out</p>
我希望下面的所有内容,包括“参考”标题都被注释掉。显然我可以使用美丽汤的提取特征来提取这样的东西:
soup = BeautifulSoup(data, "lxml")
references = soup.find("h2", text=re.compile("References"))
for elm in references.find_next_siblings():
elm.extract()
references.extract()
我也知道美丽的汤允许您像这样使用评论创建功能
from bs4 import Comment
commented_tag = Comment(chunk_of_html_parsed_somewhere_else)
soup.append(commented_tag)
这似乎非常不符合 Python 标准,而且是一种将 html 注释标签直接封装在特定标签之外的繁琐方法,尤其是当标签位于厚 html 树的中间时。难道没有更简单的方法可以让你在beautifulsoup 上找到一个标签,然后直接在其前后放置<!-- --> 吗?提前致谢。
【问题讨论】:
标签: python html beautifulsoup