解析HTML表格到Python列表? [英] Parse HTML table to Python list?

查看:735
本文介绍了解析HTML表格到Python列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个HTML表格并通过解析来得到一个字典列表。例如,如果我有一个包含三列(用标记标记标记)的HTML表格,则可以使用表格中的每一个列表元素作为对应于表格中的一行的字典。

事件,开始日期和结束日期,并且该表有5个条目,我想通过该表解析以获取长度为5的列表,其中每个元素是具有键事件,开始日期和结束日期。



感谢您的帮助!

解决方案

您应该使用一些HTML解析库,如 lxml


  from lxml import etree 
s =< table>
< tr> < th>< th>开始日期< / td>< td> a< / td>< th>结束日期< / td> ;< td> b< / td>< td> c< / td>< td> e< / td>< td> < td> f< / td>< / tr>
< tr> ;< TD>克LT; / TD>< TD> H< / TD>< TD> I< / TD>< / TR>
< / table>

table = etree.HTML(s).find(body / table)
rows = iter(table)
headers = [col.text for col在下一行(行)]
行中的行:
values = [col.text for col in row]
print dict(zip(headers,values))

打印

  {'结束日期':'c','开始日期':'b','事件':'a'} 
{'结束日期':'f','开始日期':'e','事件':'d'}
{'结束日期':'我','开始日期':'h','事件':'g'}
pre>

I'd like to take an HTML table and parse through it to get a list of dictionaries. Each list element would be a dictionary corresponding to a row in the table.

If, for example, I had an HTML table with three columns (marked by header tags), "Event", "Start Date", and "End Date" and that table had 5 entries, I would like to parse through that table to get back a list of length 5 where each element is a dictionary with keys "Event", "Start Date", and "End Date".

Thanks for the help!

解决方案

You should use some HTML parsing library like lxml:

from lxml import etree
s = """<table>
  <tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
  <tr><td>a</td><td>b</td><td>c</td></tr>
  <tr><td>d</td><td>e</td><td>f</td></tr>
  <tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""
table = etree.HTML(s).find("body/table")
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
    values = [col.text for col in row]
    print dict(zip(headers, values))

prints

{'End Date': 'c', 'Start Date': 'b', 'Event': 'a'}
{'End Date': 'f', 'Start Date': 'e', 'Event': 'd'}
{'End Date': 'i', 'Start Date': 'h', 'Event': 'g'}

这篇关于解析HTML表格到Python列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆