Convert HTML table into CSV file in python

CSV file is a Comma Separated Value file that uses a comma to separate values. CSV file is a useful thing in today’s world when we are talking about machine learning, data handling, and data visualization. In this article, we will discuss how to convert an HTML table into a CSV file.

Converting HTML Table into CSV file in Python

Example: Suppose HTML file looks like,


HTML table can be converted to CSV file using BeautifulSoup and Pandas module of Python. These modules do not comes built-in with Python. To install them type the below command in the terminal.

pip install BeautifulSoup
pip install pandas

Python3 Code for converting the HTML table into CSV file





# Importing the required modules 
import os
import sys
import pandas as pd
from bs4 import BeautifulSoup
path = 'html.html'
# empty list
data = []
# for getting the header from
# the HTML file
list_header = []
soup = BeautifulSoup(open(path),'html.parser')
header = soup.find_all("table")[0].find("tr")
for items in header:
# for getting the data 
HTML_data = soup.find_all("table")[0].find_all("tr")[1:]
for element in HTML_data:
    sub_data = []
    for sub_element in element:
# Storing the data into Pandas
# DataFrame 
dataFrame = pd.DataFrame(data = data, columns = list_header)
# Converting Pandas DataFrame
# into CSV file




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.