Pandas Reading HTML Tables
Pandas' pd.read_html() The function can automatically parse HTML table data from web pages and convert it into a DataFrame. This is very useful for scraping web data, analyzing stock prices, and retrieving financial information.
Basic Usage
read_html() The function finds and reads all HTML table elements on a web page, returning a list of DataFrames.
Read a single table
Example
import
pandas
as
pd
Read all tables on a web page
Note: requires the lxml and beautifulsoup4 libraries
pip install lxml beautifulsoup4
Read from a URL
tables
=
pd.
read_html
(
"https://example.com/table.html"
)
Check the number of tables found
(
f
"Found {len(tables)} tables"
)
Get the first table
df
=
tables
[
0
]
(
df.
head
(
)
)
Read multiple tables
A web page may contain multiple tables,read_html() a list is returned, and you can select by index:
Example
import
pandas
as
pd
Suppose the web page has multiple tables
tables
=
pd.
read_html
(
"https://example.com/data.html"
)
Iterate over all tables
for
i
,
table
in
enumerate
(
tables
)
:
(
f
"\n=== Table {i+1} ==="
)
(
f
"Shape: {table.shape}"
)
(
table.
head
(
3
)
)
Common Parameters in Detail
| Parameters | Description | Example |
|---|---|---|
io |
Input source, which can be a URL, a file path, or a string | "page.html" |
match |
Regex matching, to filter tables containing specific text | match="销售额" |
header |
Specify the header row index | header=0 |
attrs |
Filter tables by HTML attributes | attrs={"id": "table1"} |
skiprows |
Skip the specified rows | skiprows=[0, 1] |
na_values |
Specify strings to be treated as missing values | na_values=["N/A"] |
Filter tables using the match parameter
Example
import
pandas
as
pd
Use the match parameter to return only tables containing specific text
For example: read only tables containing the word "stock"
tables
=
pd.
read_html
(
"https://example.com/finance.html"
,
match
=
"stock"
)
if
tables:
df
=
tables
[
0
]
(
df
)
Locate a table precisely using the attrs parameter
Example
import
pandas
as
pd
Locate a table by HTML attributes
For example: get the table with id="stock-table"
tables
=
pd.
read_html
(
"https://example.com/data.html"
,
attrs
=
{
"id"
:
"stock-table"
}
Find the table element with id="stock-table"
)
Or locate by class
tables
=
pd.
read_html
(
"https://example.com/data.html"
,
attrs
=
{
"class"
:
"data-table"
}
)
df
=
tables
[
0
]
(
df
)
Practical example: scraping stock data from a web page
The following example demonstrates how to scrape a stock list from a financial website:
Example
import
pandas
as
pd
from
io
import
StringIO
Create a mock HTML content for demonstration
Replace with a real URL in actual use
html_content
=
'''
| Stock code | Stock name | Closing price | Change percentage |
|---|---|---|---|
| 600519 | Kweichow Moutai | 1850.00 | 2.35% |
| 000858 | Wuliangye | 185.50 | -1.20% |
| 601318 | Ping An Insurance | 52.30 | 0.85% |
Read a table from a string
tables
=
pd.
read_html
(
StringIO
(
html_content
)
)
df
=
tables
[
0
]
(
"Original table:"
)
(
df
)
(
)
Data cleaning: handling the change percentage column
df
[
"Change percentage"
]
=
df
[
"Change percentage"
]
.
str
.
replace
(
"%"
,
""
)
.
astype
(
float
)
df
[
"Closing price"
]
=
df
[
"Closing price"
]
.
astype
(
float
)
(
"Cleaned data:"
)
(
df
)
StringIO works by disguising a string as a file object, so pandas processes it following the logic for reading a file stream, instead of mistaking it for a path or URL.
Output:
Original table:
股票代码 股票名称 收盘价 涨跌幅
0 600519 贵州茅台 1850.0 2.35%
1 858 五粮液 185.5 -1.20%
2 601318 中国平安 52.3 0.85%
Cleaned data:
股票代码 股票名称 收盘价 涨跌幅
0 600519 贵州茅台 1850.0 2.35
1 858 五粮液 185.5 -1.20
2 601318 中国平安 52.3 0.85
Read Wikipedia tables
Example
import
pandas
as
pd
Read tables from a Wikipedia page
Take the list of countries by population as an example
url
=
"https://en.wikipedia.org/wiki/List_of_countries_by_population_(United_Nations)"
try
:
tables
=
pd.
read_html
(
url
)
(
f
"This page has {len(tables)} tables in total"
)
Usually the first table is the one we need
df
=
tables
[
0
]
(
df.
head
(
10
)
)
except
Exception
as
e:
(
f
"Read failed: {e}"
)
(
"Make sure the required libraries are installed: pip install lxml beautifulsoup4"
)
Data Cleaning and Processing
Tables read from web pages usually need further cleaning before they can be used for analysis.
Common cleaning operations
Example
import
pandas
as
pd
from
io
import
StringIO
Simulate a table containing various kinds of dirty data
html_content
=
'''
| Date | Product | Sales | Notes |
|---|---|---|---|
| 2024-01-01 | Product A | 1,234 | N/A |
| 2024-01-02 | Product B | 567 | Out of stock |
| 2024-01-03 | Product C | -- | Not counted |
df
=
pd.
read_html
(
StringIO
(
html_content
)
)
[
0
]
(
"Original data:"
)
(
df
)
(
)
Cleaning steps
1. Rename columns
df.
columns
=
[
"date"
,
"Product"
,
"Sales"
,
"Remarks"
]
2. Handle missing values
df
=
df.
replace
(
[
"N/A"
,
"--"
,
"Not counted"
,
"Out of stock"
]
,
pd.
NA
)
3. Clean numeric columns (remove commas)
df
[
"Sales"
]
=
df
[
"Sales"
]
.
str
.
replace
(
","
,
""
)
.
replace
(
pd.
NA
,
None
)
df
[
"Sales"
]
=
pd.
to_numeric
(
df
[
"Sales"
]
,
errors
=
"coerce"
)
4. Convert dates
df
[
"date"
]
=
pd.
to_datetime
(
df
[
"date"
]
)
(
"After cleaning:"
)
(
df
)
(
"\nData types:"
)
(
df.
dtypes
)
Output:
Original data:
日期 产品 销量 备注
0 2024-01-01 产品A 1234 NaN
1 2024-01-02 产品B 567 缺货
2 2024-01-03 产品C -- 未统计
After cleaning:
日期 产品 销量 备注
0 2024-01-01 产品A 1234.0 NaN
1 2024-01-02 产品B 567.0
2 2024-01-03 产品C NaN
Data type:
日期 datetime64[ns]
产品 object
销量 float64
备注 object
dtype: object
Notes and common issues
1. Install dependencies
read_html() Needed lxml and beautifulsoup4 Libraries:
pip install lxml beautifulsoup4
2. Network issues
When reading a web URL, you may encounter network latency or access restrictions; it is recommended to add appropriate timeout settings or use a local cache.
3. Complex table structure
Some web pages use complex table structures such as merged cells and nested tables, which may cause parsing to fail. In such cases, you can try using BeautifulSoup to parse the HTML directly.
4. Data integrity
Web data may change at any time; it is recommended to verify data integrity after reading and compare it with the original data source.
When scraping web data, please comply with the website's robots.txt rules and relevant laws and regulations, and avoid frequent requests so as not to burden the server.
Summary
pd.read_html() It is a powerful tool for scraping web table data, quickly converting HTML tables into DataFrames. In practical use, you need to pay attention to installing dependencies, handling network issues, and cleaning dirty data. Scraped data usually needs further processing before analysis, so it is recommended to use it together with Pandas' data cleaning features.