【问题标题】:Is there a way to parse html tags with Python?有没有办法用 Python 解析 html 标签?
【发布时间】:2021-10-28 03:04:13
【问题描述】:

我需要解析几个 HTML 标签。

示例: 我需要转:

<div class="title">
     <h1> Hello World </h1>
</div>

进入

['<div class="title">', '<h1> Hello World </h1>', '</div>']

【问题讨论】:

  • 你可以用ElementTree.iterparse 来做这个例子,但它适用于格式良好的 XML,而不是凌乱的 HTML。还有 lxml 的 iterwalk here - 在这种情况下使用 lxml 的 html 解析器来构建文档,然后使用 iterwalk 来获取开始和结束标签。

标签: python html-parsing


【解决方案1】:

你可以使用 ('>

并再次将“>

【讨论】:

  • 这会解析单个标签,我需要解析带有嵌套内容的标签。我的输出是['&lt;', '&lt;div class="title"&gt; ', '&lt;h1&gt; Hello World ', '&lt;/h1&gt; ', '&lt;/div&gt;'],但是,我需要['&lt;div class="title"&gt;', '&lt;h1&gt; Hello World &lt;/h1&gt;', '&lt;/div&gt;']。
  • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
【解决方案2】:

您可以将递归生成器函数与BeautifulSoup 一起使用:

import bs4
from bs4 import BeautifulSoup as soup
s = """
<div class="title">
   <h1> Hello World </h1>
</div>
"""
def get_tags(d):
   ats = " ".join(a+"="+f'"{(b if not isinstance(b, list) else " ".join(b))}"' for a, b in d.attrs.items())
   h = f'<{d.name} {ats}>' if ats else f'<{d.name}>'
   if (k:=[i for i in d.contents if isinstance(i, bs4.element.Tag)]):
      yield h
      yield from [j for l in k for j in get_tags(l)]
      yield f'</{d.name}>'
   else:
      yield f'{h}{d.text}</{d.name}>'

print(list(get_tags(soup(s, 'html.parser').contents[1])))

输出:

['<div class="title">', '<h1> Hello World </h1>', '</div>']

【讨论】:

  • @MyDisplay 很高兴为您提供帮助!
猜你喜欢
  • 2020-11-01
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 2012-02-24
  • 2015-10-06
  • 1970-01-01
  • 2022-07-10
  • 1970-01-01
相关资源
最近更新 更多