如何将一个HTML表格转换为python中的一个数组 [英] How to convert an HTML table to an array in python

查看:139
本文介绍了如何将一个HTML表格转换为python中的一个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html文档,我想从这个文档中提取表格并将它们作为数组返回。我写了两个函数,一个用于查找文档中的所有html表格,另一个用于将html表格转换为二维数组。



类似这样的东西:

  htmltables = get_tables(htmldocument)
用于htmltables中的表格:
array = make_array(table)

有两个捕获点:$ b​​ $ b 1.数量表每天都在变化
2.这些表格有各种奇怪的额外格式,如粗体和闪烁标签,随机抛出。

谢谢!

解决方案

熊猫可以提取您的所有表格HTML到开箱即用的数据框列表,让您无需自己解析页面(重新发明轮子)。 DataFrame 是一种功能强大的二维数组。

我建议通过Pandas继续使用这些数据,因为它是一个很棒的工具,但是如果您愿意,也可以转换为其他格式(列表,字典,csv文件,
$ b

 从HTML文件中提取所有表格,打印并保存到csv文件中。

将pandas导入为pd

df_list = pd.read_html(' my_file.html')

for i,df in enumerate(df_list):
print df
df.to_csv('table {} .csv'.format(i))

直接从网页而不是文件获取html内容只需要稍作修改:

 导入请求

html = requests.get('my_url')。content
df_list = pd.read_html(html)


I have an html document, and I want to pull the tables out of this document and return them as arrays. I'm picturing 2 functions, one that finds all the html tables in a document, and a second one that turns html tables into 2-dimensional arrays.

Something like this:

htmltables = get_tables(htmldocument)
for table in htmltables:
    array=make_array(table)

There's 2 catches: 1. The number tables varies day to day 2. The tables have all kinds of weird extra formatting, like bold and blink tags, randomly thrown in.

Thanks!

解决方案

Pandas can extract all of the tables in your html to a list of dataframes right out of the box, saving you from having to parse the page yourself (reinventing the wheel). A DataFrame is a powerful type of 2-dimensional array.

I recommend continuing to work with the data via Pandas since it's a great tool, but you can also convert to other formats if you prefer (list, dictionary, csv file, etc.).

Example

"""Extract all tables from an html file, printing and saving each to csv file."""

import pandas as pd

df_list = pd.read_html('my_file.html')

for i, df in enumerate(df_list):
    print df
    df.to_csv('table {}.csv'.format(i))

Getting the html content directly from the web instead of from a file would only require a slight modification:

import requests

html = requests.get('my_url').content
df_list = pd.read_html(html)

这篇关于如何将一个HTML表格转换为python中的一个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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