1

如何使用 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",}

}

非常感谢。

4

2 回答 2

4

简单的方法:

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'}})
于 2014-01-09T21:40:55.297 回答
0

像这样的东西......虽然我不确定我对 pyquery 的感觉(试试 BeautifulSoup)

from pyquery import PyQuery as pq

>>> p = pq(html)
>>> p = d(".properties_label span")
>>> for x in p:
...   print x.text
...
cat1_el1_label
cat2_el1_label
cat3_el1_label

>>> p = d(".properties_value")
>>> for x in p:
...   print x.text
...
cat1_el1_value
cat2_el1_value
cat3_el1_value
于 2013-12-16T23:55:02.610 回答