python从PDF文件中爬取表格数据 - camelot

简介

camelot是Python的一个模块,它能够让任何人轻松地从PDF文件中提取表格数据。

(安装时间较长):pip install camelot-py

camelot模块的官方文档地址为:https://camelot-py.readthedocs.io/en/master/

 

案例

首先,让我们看一个简单的例子:eg.pdf,整个文件只有一页,这一页中只有一个表格,如下: 

python从PDF文件中爬取表格数据 - camelot_第1张图片

 使用以下Python代码就可以提取该PDF文件中的表格:

import camelot

# 从PDF文件中提取表格
tables = camelot.read_pdf('E://eg.pdf', pages='1', flavor='stream')

# 表格信息
print(tables)
print(tables[0])
# 表格数据
print(tables[0].data)

输出结果为:



[['ID', '姓名', '城市', '性别'], ['1', 'Alex', 'Shanghai', 'M'], ['2', 'Bob', 'Beijing', 'F'], ['3', 'Cook', 'New York', 'M']]

分析代码

camelot.read_pdf()  为camelot的从表格中提取数据的函数,输入的参数为PDF文件的路径,页码(pages)和表格解析方法(有stream和lattice两个方法)。

对于表格解析方法,默认的方法为lattice,而stream方法默认会把整个PDF页面当做一个表格来解析,如果需要指定解析页面中的区域,可以使用table_area这个参数。

 

camelot模块的便捷之处还在于它提供了将提取后的表格数据直接转化为pandas,csv,JSON,html的函数,如tables[0].df,tables[0].to_csv()函数等

我们以输出csv文件为例:

import camelot

# 从PDF文件中提取表格
tables = camelot.read_pdf('E://eg.pdf', pages='1', flavor='stream')

# 将表格数据转化为csv文件
tables[0].to_csv('E://eg.csv')

得到的csv文件如下:

python从PDF文件中爬取表格数据 - camelot_第2张图片

 

例2,提取PDF页面中的某一区域的表格的数据。

python从PDF文件中爬取表格数据 - camelot_第3张图片

为了提取整个页面中唯一的表格,我们需要定位表格所在的位置。

PDF文件的坐标系统与图片不一样,它以左下角的顶点为原点,向右为x轴,向上为y轴,可以通过以下Python代码输出整个页面的文字的坐标情况:

import camelot

# 识别指定区域中的表格数据
tables = camelot.read_pdf('G://Statistics-Fundamentals-Succinctly.pdf', pages='53', \
                          flavor='stream', table_area=['50,620,500,540'])

# 绘制PDF文档的坐标,定位表格所在的位置
table_df = tables[0].df

print(type(table_df))
print(table_df.head(n=6))

stream方法默认将整个PDF页面当作表格

table_area参数则是确定表格具体位置

结果:


         0               1                2           3
0  Student  Pre-test score  Post-test score  Difference
1        1              70               73           3
2        2              64               65           1
3        3              69               63          -6
4        …               …                …           …
5       34              82               88           6

 

你可能感兴趣的:(扩展知识,python学习)