Python 3 Script to Convert HTML Table to CSV File Using Pandas and BeautifulSoup4 Library Full Tutorial For Beginners


Welcome folks today in this post we will be converting html table to csv file in python script using pandas and beautifulsoup4 library. All the full source code of the application is given below.




Get Started



In order to get started you need to install the following libraries by using the pip command


pip install beautifulsoup4


pip install pandas


After installing all the libraries you need to create an table.html inside the root directory and here you need to copy paste the html code for generating a simple table




<!DOCTYPE html>
<html lang="en">
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="">
  <script src=""></script>
  <script src=""></script>

<div class="container">
  <h2>Basic Table</h2>
  <p>The .table class adds basic styling (light padding and only horizontal dividers) to a table:</p>            
  <table class="table">




So here if you open this file inside the browser it will show the table which we will convert to csv file in python script

See also  Python 3 Tkinter Script to Build Ludo Dice Rolling GUI Game Full Project For Beginners




So after this you need to make an file and copy paste the following code


# Importing the required modules 
import os 
import sys 
import pandas as pd 
from bs4 import BeautifulSoup 

path = 'table.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 



So now if you execute this python script by the below command




Now you will see it will create the csv file as shown below





Leave a Reply