Pandas pd.read_html() function
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
- Return Type:
listof DataFrames - returns a list of DataFrames; there is one DataFrame for each table on the page.
- If no matching table is found, an empty list is returned.
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
=
'''
Pandas pd-read-html() function
| Name | Age | City | Salary |
|---|---|---|---|
| Tom | 28 | Beijing | 8000 |
| Jerry | 35 | Shanghai | 12000 |
| Mike | 42 | Guangzhou | 15000 |
| Lucy | 26 | Shenzhen | 7000 |
department list
| Department | Count |
|---|---|
| Engineering | 50 |
| Sales | 30 |
'''
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
(
f
"found {len(tables)} tables in total"
)
(
)
Iterate over all tables
for
i
,
df
in
enumerate
(
tables
)
:
(
f
"--- table {i+1} ---"
)
(
df
)
(
)
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:
read_html()returns a list of DataFrames, with one DataFrame per table.- By default, all tables are read.
- The first row is automatically recognized as column names (because there is a
thtags).
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'
}
)
(
"filtered by id:"
)
(
tables_by_id
[
0
]
)
(
)
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'
}
)
(
"filtered by class (found {} tables):"
.
format
(
len
(
tables_by_class
)
)
)
for
i
,
df
in
enumerate
(
tables_by_class
)
:
(
f
"table {i+1}:"
)
(
df
)
(
)
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'
)
(
"tables containing the text 'Tom':"
)
(
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:
attrsThe parameter can specify HTML tag attributes (such as id, class, style, etc.) to filter tables.matchThe parameter uses a regular expression to match text content in tables and returns tables containing matching text.- When only one table is returned, you can use
tables[0]to get the first DataFrame.
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 | ||
| 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
]
(
"no header:"
)
(
df_no_header
)
(
)
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
]
(
"multi-row header:"
)
(
df_multi_header
)
(
)
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
]
(
"set index:"
)
(
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:
header=NoneYou can disable automatic header detection and use the default integer index as column names.- Multi-row headers are processed as a multi-level index (MultiIndex).
index_colThe parameter can specify a column as the row index.
Notes
- Use
read_html()Installation requiredlxmlLibraries:pip install lxml。 - The return value is a list of DataFrames, so you need to select the specific table by index.
- When a page has multiple tables, use the
attrsormatchparameter to filter them. read_html()tries to parse all tables, which can be slow; for large pages you can use thematchparameter to narrow the scope.- Reading web pages requires network access and may be subject to access restrictions or anti-scraping mechanisms.
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.
Common Pandas functions