【问题标题】:Split a HTML document at tag - Python在标签处拆分 HTML 文档 - Python
【发布时间】:2012-09-25 23:15:21
【问题描述】:

根据
标签的出现来拆分 HTML 文档/字符串的最佳方法是什么?我在下面给出了我目前拥有的解决方案,但它看起来很麻烦,而且我认为并不是那么容易阅读。我也尝试了正则表达式,但我被告知我不应该使用正则表达式来解析 HTML

for i, br in enumerate(soup.findAll('b')):
line_value = ''
line_values = []
next = br.next
while (next):
    if next and isinstance(next, Tag) and next.name == 'br':
        line_values.append(line_value)
        line_value = ''
    else:
        stripped_text = ''.join(BeautifulSoup(str(next).strip()).findAll(text=True))
        if stripped_text:
            line_value += stripped_text
    next = next.nextSibling
print line_values

这是我正在解析的 HTML 示例:

<p><font size="1" color="#800000"><b>09:00
  <font> - </font>
  11:00
  <br>
  CE4817
  <font> - </font>LAB <font>- </font>
  2A
  <br>
   B2043 B2042
  <br>

  Wks:1-13
  </b></font>
  </p>

以及我的代码的当前结果:

[u'09:00 - 11:00', u'CE4817 - LAB- 2A', u'B2043 B2042']
[u'11:00 - 12:00', u'CE4607 - TUT- 3A', u'A1054']

【问题讨论】:

  • 我要澄清一下:您需要拆分给定标签的html文档还是只从输入中删除所有标签?
  • 我需要根据 br 标签(或其他指定标签)的出现进行拆分

标签: python html regex parsing beautifulsoup


【解决方案1】:

试试这个:

正则表达式

<p><font size="1" color="#800000"><b>(\d{2}:\d{2}).*?(\d{2}:\d{2}).*?(\w{2}\d{4}).*?<font> - </font>(\w+)\s*<font>- </font>\s*(\d\w)\s*<br>\s*(\w\d{4}\s*\w\d{4})\s*<br>[\s\S]*?</p>

模式

m - 多行

只要 html 代码的结构不变,这将起作用。

【讨论】:

    【解决方案2】:

    用正则表达式分割

    import re
    p = re.compile(r'<br>')
    filter(None, p.split(yourString))
    

    然后您可以从数组中每个返回的字符串中删除其他 html 标记。

    您可以使用现有函数,如Strip html from strings in python 或查看我对问题Stripping HTML tags without using HtmlAgilityPack 的回答。

    还要检查这个答案:RegEx match open tags except XHTML self-contained tags

    你应该真的使用 html 解析器来完成你的任务

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多