Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas pd.read_html() function

Pandas pd.read_html() function

Python math Module Common Pandas functions


read_html() is a function in the pandas library for parsing HTML tables; it can read table data from web pages or HTML files and convert it into a DataFrame.

Table data on web pages is a very important data source; much public data (such as stock information and statistics) is presented as HTML tables.read_html() Use lxml and BeautifulSoup library to parse HTML and automatically extract all tables or specified tables from a page.


Basic syntax and parameters

Syntax format



pandas.read_html(io, match='.+', flavor=None, header=None, index_col=None,

                skiprows=None, attrs=None, parse_dates=False, thousands=',',

                decimal='.', converters=None, ...)

Parameter Description

Parameters Type Description Default value
io str, path object, file-like object an HTML file path, URL, or string Required
match str, regex use a regular expression to match the text content of tables '.+'
flavor str parser: 'lxml', 'html5lib', 'bs4' None
header int, list of int the row number to use as column names None
index_col int, str Column used as the row index None
skiprows int, list, slice skip the specified rows None
attrs dict HTML tag attributes used to filter tables None
parse_dates bool, list whether to parse date columns False

Return Value


Example

Through the following examples, fully master read_html() its various usages.

Example 1: read tables from a local HTML file

First create an HTML file containing a table, then use read_html() to read it.

Example

import

pandas

as

pd

Create an HTML file containing a table

html_content

=

'''

    employee information table

   

Pandas pd-read-html() function


   






























                                                                                                                                                                                                                                                                                                                                   
NameAgeCitySalary
Tom28Beijing8000
Jerry35Shanghai12000
Mike42Guangzhou15000
Lucy26Shenzhen7000

   

department list


   












                                                                                                                           
DepartmentCount
Engineering50
Sales30

'''

Write the HTML to a file

with

open

(

'tables.html'

,

'w'

,

encoding

=

'utf-8'

)

as

f:

    f.

write

(

html_content

)

Use read_html to read all tables

io: HTML file path (required)

tables

=

pd.

read_html

(

'tables.html'

)

View the reading result

print

(

f

"found {len(tables)} tables in total"

)

print

(

)

Iterate over all tables

for

i

,

df

in

enumerate

(

tables

)

:

   

print

(

f

"--- table {i+1} ---"

)

   

print

(

df

)

   

print

(

)

Expected output:



共找到 2 个表格



--- 表格 1 ---

    姓名  年龄       城市    薪资

0   Tom   28    Beijing   8000

1  Jerry   35   Shanghai  12000

2   Mike   42  Guangzhou  15000

3   Lucy   26  Shenzhen   7000



--- 表格 2 ---

    部门  人数

0  技术部   50

1  销售部   30

Code analysis:

Example 2: use attrs and match to filter tables

When a page has multiple tables, you can use attribute or text matching to filter the tables you need.

Example

import

pandas

as

pd

Create an HTML file with attributes

html_with_attrs

=

'''

   





                           
name age
Tom 28
Jerry 35

   





                           
product price
A 100
B 200

   



           
Total 2

'''

with

open

(

'tables_attrs.html'

,

'w'

,

encoding

=

'utf-8'

)

as

f:

    f.

write

(

html_with_attrs

)

Example 2a: use attrs to filter by the id attribute

Read the table with id="employees"

tables_by_id

=

pd.

read_html

(

'tables_attrs.html'

,

attrs

=

{

'id'

:

'employees'

}

)

print

(

"filtered by id:"

)

print

(

tables_by_id

[

0

]

)

print

(

)

Example 2b: use attrs to filter by the class attribute

Read all tables with class="data-table"

tables_by_class

=

pd.

read_html

(

'tables_attrs.html'

,

attrs

=

{

'class'

:

'data-table'

}

)

print

(

"filtered by class (found {} tables):"

.

format

(

len

(

tables_by_class

)

)

)

for

i

,

df

in

enumerate

(

tables_by_class

)

:

   

print

(

f

"table {i+1}:"

)

   

print

(

df

)

   

print

(

)

Example 2c: use match to filter tables containing specific text

match uses a regular expression to match text in tables

tables_by_text

=

pd.

read_html

(

'tables_attrs.html'

,

match

=

'Tom'

)

print

(

"tables containing the text 'Tom':"

)

print

(

tables_by_text

[

0

]

)

Expected output:



# Filter by id:

   name  age

0   Tom   28

1  Jerry   35



使用 class 筛选 (找到 2 个表格):

表格 1:

   name  age

0   Tom   28

1  Jerry   35



表格 2:

  product  price

0       A    100

1       B    200



Table containing the text 'Tom':

   name  age

0   Tom   28

1  Jerry   35

Code analysis:

Example 3: handling headers and indexes

HTML tables can have complex formats that require flexible handling of headers and indexes.

h2 class="example">Example

import

pandas

as

pd

Create HTML with a complex structure

html_complex

=

'''

   
   




                   
Tom 28
Jerry 35

   
   






                                   
Name Contact information
Phone Email
Tom 123456 tom@runoob.com
Jerry 789012 jerry@runoob.com

   
   





                           
Name Age City
Tom 28 Beijing

'''

with

open

(

'tables_complex.html'

,

'w'

,

encoding

=

'utf-8'

)

as

f:

    f.

write

(

html_complex

)

Example 3a: when there is no header

header=None does not use the first row as column names

df_no_header

=

pd.

read_html

(

'tables_complex.html'

,

attrs

=

{

'id'

:

'no_header'

}

,

header

=

None

)

[

0

]

print

(

"no header:"

)

print

(

df_no_header

)

print

(

)

Example 3b: multi-row headers

Use rows 0 and 1 together as the header

df_multi_header

=

pd.

read_html

(

'tables_complex.html'

,

attrs

=

{

'id'

:

'multi_header'

}

)

[

0

]

print

(

"multi-row header:"

)

print

(

df_multi_header

)

print

(

)

Example 3c: set an index column

index_col specifies column 0 as the index

df_with_index

=

pd.

read_html

(

'tables_complex.html'

,

attrs

=

{

'id'

:

'with_index'

}

,

index_col

=

0

)

[

0

]

print

(

"set index:"

)

print

(

df_with_index

)

Expected output:



No header:

      0     1

0  Tom    28

1  Jerry  35



Multi-line header:

       姓名    联系方式

        NaN    电话          邮箱

0     Tom  123456  tom@runoob.com

1   Jerry  789012  jerry@runoob.com



Set index:

                年龄       城市

姓名

Tom            28    Beijing



空字符串    NaN       NaN

Tom            28    Beijing

Code analysis:


Notes


Summary

read_html() is a powerful tool in pandas for reading HTML table data. It can automatically parse tables in web pages and convert them into structured DataFrames.

In real work, if you need to get data from web pages,read_html() is a very practical choice. Mastering the attrs and match parameters lets you efficiently extract the data you need from complex pages. Readers are encouraged to consider this function first when scraping web tables.

Python math Module Common Pandas functions