python - 如何使用pyquery解析HTML表格?

标签 python html pyquery

如何使用pyquery解析HTML表格? [参见 http://pastie.org/pastes/8556919 上的源代码 html 表

结果: {

"category_1":{ "cat1_el1_label":"cat1_el1_value",},

"category_2":{"cat2_el1_label":"cat2_el1_value",},

"category_3":{"cat3_el1_label":"cat3_el1_value",}

非常感谢。

最佳答案

简单的方法:

from pyquery import PyQuery
from collections import defaultdict

doc = PyQuery(html)
values = defaultdict(dict)
for tr in doc('tr').items():
    if tr('th.title'):
        title = tr('th.title').text()
    else:
        items = zip(tr('.properties_label').items(),
                    tr('.properties_value').items())
        values[title].update(dict([(k.text(), v.text()) for k, v in items]))

结果:

defaultdict(<type 'dict'>, {'Category_3': {'cat3_el1_label': 'cat3_el1_value'},
                            'Category_2': {'cat2_el1_label': 'cat2_el1_value'},
                            'Category_1': {'cat1_el1_label': 'cat1_el1_value'}})

关于python - 如何使用pyquery解析HTML表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20622811/

相关文章:

python - 在 python 中使用队列

javascript - 为什么我的某些选项卡会导致我的内容稍微向右移动?

.net - 在 .Net 中阅读和编辑 HTML

python - 如何在将 pyquery 对象转换为字符串时取消转义特殊字符

python - 使用 Pyquery、Requests 和 Gadget 选择器提取 Web 元素

Python 将变量视为文字/原始字符串

python:在for循环中获取下一个项目

javascript - 根据 javascript 值显示文本或标签

python - 广告扰乱了我的文章爬行

python - 从 python 中的嵌套 JSON 文件访问值