如何在python中将HTML表转换为数组

Zac*_*ach 13 html python

我有一个html文档,我想从本文档中拉出表格并将它们作为数组返回.我正在想象2个函数,一个用于查找文档中的所有html表,另一个用于将html表转换为二维数组.

像这样的东西:

htmltables = get_tables(htmldocument)
for table in htmltables:
    array=make_array(table)
Run Code Online (Sandbox Code Playgroud)

有2个捕获:1.数字表每天都有所不同.这些表有各种奇怪的额外格式,如粗体和闪烁标签,随机抛出.

谢谢!

Ale*_*lli 18

使用BeautifulSoup(我推荐3.0.8).查找所有表格是微不足道的:

import BeautifulSoup

def get_tables(htmldoc):
    soup = BeautifulSoup.BeautifulSoup(htmldoc)
    return soup.findAll('table')
Run Code Online (Sandbox Code Playgroud)

然而,在Python,一个阵列是一维和约束到漂亮的基本类型作为项目(整数,浮点数,初级).所以没有办法在Python中挤压HTML表格array.

也许你的意思是Python list而不是?这也是一维的,但任何东西都可以是一个项目,所以你可以有一个列表列表(每个tr标签一个子列表,我想,每个td标签包含一个项目).

这会给:

def makelist(table):
  result = []
  allrows = table.findAll('tr')
  for row in allrows:
    result.append([])
    allcols = row.findAll('td')
    for col in allcols:
      thestrings = [unicode(s) for s in col.findAll(text=True)]
      thetext = ''.join(thestrings)
      result[-1].append(thetext)
  return result
Run Code Online (Sandbox Code Playgroud)

这可能还不是你想要的(不会跳过HTML注释,子列表的项目是unicode字符串而不是字节字符串等)但它应该很容易调整.

  • 美丽的汤既好又容易!如果需要更高的速度,也可以尝试使用 lxml+xpath。 (2认同)

Mar*_*ese 5

Pandas可以开箱即用地将 html 中的所有表格提取到数据框列表中,从而使您不必自己解析页面(重新发明轮子)。甲数据帧是一个强大的类型2维阵列的。

我建议继续通过 Pandas 处理数据,因为它是一个很棒的工具,但如果您愿意,也可以转换为其他格式(列表、字典、csv 文件等)。

例子

"""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))
Run Code Online (Sandbox Code Playgroud)

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

import requests

html = requests.get('my_url').content
df_list = pd.read_html(html)
Run Code Online (Sandbox Code Playgroud)