代码之家  ›  专栏  ›  技术社区  ›  user8188893

使用BeautifulSoup提取HTML注释中标记内的文本

  •  0
  • user8188893  · 技术社区  · 7 年前

    我想在没有列表标记的注释中提取列表元素中的文本。但我无法使用下面的代码。

    from bs4 import BeautifulSoup, Comment
    
    
    html = """
    <html>
    <body>
    <!--
      <ul>
         <li>10</li>
         <li>20</li>
         <li>30</li>
         </ul>
     -->
    
    </body>
    </html>
    """
    soup = BeautifulSoup(html, 'html.parser')
    
    for numbers in soup.findAll(text=lambda text:isinstance(text, Comment)):
        print(numbers.extract())
    

    结果是:

    <ul>
    <li>10</li>
    <li>20</li>
    <li>30</li>
    </ul>
    

    预期结果:

    10
    20
    30
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   SIM    7 年前

    尝试以下方法。它会给你带来你想要的结果。

    from bs4 import BeautifulSoup, Comment
    
    html = """
    <html>
    <body>
    <!--
      <ul>
         <li>10</li>
         <li>20</li>
         <li>30</li>
         </ul>
     -->
    
    </body>
    </html>
    """
    soup = BeautifulSoup(html, 'html.parser')
    
    for item in soup.find_all(text=lambda text:isinstance(text, Comment)):
        data = BeautifulSoup(item,"html.parser")
        for number in data.find_all("li"):
            print(number.text)
    

    输出:

    10
    20
    30
    
        2
  •  0
  •   gout    7 年前

    查找所有“li”,只打印文本。

    for tag in soup.find_all("li"):
            print(tag.text))