【发布时间】: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