我正在使用 Python + xPath 来解析一些 HTML,但在解析定义列表时遇到了问题。一个例子如下:
<dl><br/>
<dt>Section One</dt><br/>
<dd>Child one</dd><br/>
<dd>Child one.2</dd><br/>
<dt>Section Two</dt><br/>
<dd>Child two</dd><br/>
</dl>
我想将其转换为如下输出:
{'Section One' : ['Child one','Child one.2'], 'Section Two' : ['Child two']}
不过我遇到了困难,因为它的结构方式与您在输出中找到的层次结构不同。
谢谢
最佳答案
没有 xpath 的解决方案,使用 lxml(如果您正在使用 xpath,您可能已经在使用它?):
from collections import defaultdict
from lxml import etree
dl = etree.fromstring('''<dl>
<dt>Section One</dt>
<dd>Child one</dd>
<dd>Child one.2</dd>
<dt>Section Two</dt>
<dd>Child two</dd>
</dl>''')
result = defaultdict(list)
for dt in dl.findall('dt'):
for child in dt.itersiblings(): # iterate over following siblings
if child.tag != 'dd':
break # stop at the first element that is not a dd
result[dt.text].append(child.text)
print dict(result)
(我能想出的任何 xpath 解决方案似乎都比这更糟糕)
关于python - 使用 XPath 解析定义列表的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4968633/