python - 使用 XPath 解析定义列表的最佳方法是什么?

标签 python xslt xpath

我正在使用 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/

相关文章:

python - Pandas 类型错误: unhashable type: 'slice'

python - elif 使用字典但不执行值

java - 如何将 BIRT 与 Python 集成

html - 使用 Perl XML::XSLT 生成 OUTLOOK 有问题的 HTML

java - HTML 标签的 XPATH 写入在文本前后包含空格,即 <button>spaces text space</button>?

python - 如何使用 scrapy 和 python 动态抓取 Tripadvisor

xslt - 如何使用xpath从多组计算值中获取最大值或最小值

python - 无法让 Django 管理员在 Apache 上查找静态文件(css、img、js)

jquery - 从一个 XML XSLT 到 HTML 制作两列

java - 在 XML 上应用 XSLT 以获得格式化(彩色)输出