【问题标题】:Beautiful Soup: Best ways to comment out a tag instead of extracting it?Beautiful Soup:注释掉标签而不是提取标签的最佳方法?
【发布时间】: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 上找到一个标签,然后直接在其前后放置&lt;!-- --&gt; 吗?提前致谢。

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    假设我正确理解了问题,您可以使用replace_with() 将标签替换为Comment 实例。这可能是评论现有标签的最简单方法:

    import re
    
    from bs4 import BeautifulSoup, Comment
    
    data = """
    <div>
        <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>
    </div>"""
    
    soup = BeautifulSoup(data, "lxml")
    elm = soup.find("h2", text=re.compile("References"))
    elm.replace_with(Comment(str(elm)))
    
    print(soup.prettify())
    

    打印:

    <html>
     <body>
      <div>
       <h1>
        Name of Article
       </h1>
       <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>
      </div>
     </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多