【发布时间】:2018-01-24 21:07:14
【问题描述】:
借助有关HTMLParser 和此stackoverflow post 的文档,我尝试从表中提取数据,同时从<td>..</td> 之间的表中提取数据,并将其附加到列表中appends 新项目当它有新的starttag 时。
下面是一个解释我的问题的小例子:
from HTMLParser import HTMLParser
class MyHTMLParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.in_td = False
self._out = []
def handle_starttag(self, tag, attrs):
if tag == 'td':
self.in_td = True
def handle_endtag(self, tag):
self.in_td = False
def handle_data(self, data):
if self.in_td:
#print(data)
self._out.append(data)
if __name__ == "__main__":
parser = MyHTMLParser()
link_raw = """
<html><p><center><h1> Clash Report 1 </h1></center></p><p><table border=on> <th> Errors </th><th> Elements </th>
<tr> <td> Delete one of those. </td>
<td> 060 : <Room Separation> : Model Lines : id 549036 <br> 060 : <Room Separation> : Model Lines : id 549042</td></tr>
<tr> <td> Delete one of those. </td>
<td> 060 : <Room Separation> : Model Lines : id 549036 <br> 060 : <Room Separation> : Model Lines : id 549081</td></tr>
"""
#<html><head><title>Test</title></head><body><tr><td>yes</td><td>no</td></tr></body></html>
parser.feed(link_raw)
print (parser._out)
输出
[' Delete one of those. ', ' 060 : ', ' : Model Lines : id 549036 ', ' 060 : ', ' : Model Lines : id 549042', ' Delete one of those. ', ' 060 : ', ' : Model Lines : id 549036 ', ' 060 : ', ' : Model Lines : id 549081']
如何忽略<Room Separation> 和<br> 等标签,仅将<td>..</td> 之间的数据附加到这样的一项
所需的输出 ['删除其中一个。 ', ' 060 : : 模型线 : id 549036 ', ' 060 : : 模型线 : id 549042', ' 删除 其中的一个。 ', ' 060 : : 型号线 : id 549036 ', ' 060 : : 模型线:id 549081']
【问题讨论】:
-
HTMLParser 是一种非常老式的 HTML 解析方式。你确定要这样做吗?
-
我实际上不想,但我想不出任何方法可以在 IronPython 中使用漂亮的汤或其他模块!
-
嗯,这就解释了。
-
恐怕我听不懂。你似乎成功了。
-
嗯,我似乎有但不完全。由于表 data
之间有 和
等标签,因此输出列表中有 10 个项目。另一方面,所需的输出只有 6 个项目,这是我需要的。
标签: python-2.7 html-table html-parsing