I am trying to extract multiple tables from the BLS website and am hitting a roadblock of sorts. I can extract the tables, I looked at other SO posts for that - (How to read an html table with multiple tbodies with python pandas' read_html?). The tables that I extract however are not formatted correctly and the data is all over the place. Here is what I have done till now;
import urllib
import pandas as pd
from bs4 import BeautifulSoup
def new_func():
url = input('Please enter the BLS publication that you want to scrape table from:')
return url
url = new_func()
data = urllib.request.urlopen(url).read()
sp = BeautifulSoup(data,'html.parser')
#unwrap multiple table tags in the html
for table in sp.findChildren(attrs={'id': 'regular'}):
for c in table.children:
if c.name in ['tbody', 'thead']:
c.unwrap()
#dataset creation
data_pandas = pd.read_html(str(sp), flavor="bs4",thousands=',',decimal='.')
#clean dataset
df = pd.concat(data_pandas, axis=0)#to convert lists of pd.read_html to dataframe
#export to csv
df.to_csv(input('Specify .csv filename:'))
The code works for a page with a single table but when it is a url like - https://www.bls.gov/regions/new-york-new-jersey/news-release/2022/occupationalemploymentandwages_kingston_20220616.htm, it seems to stop working and messes up the formatting.
I apologize if my code is messy or redundant in certain blocks - this is my first foray into Python and am struggling to figure this out. Any help or guidance on what I should look to solve this issue is appreciated.