I am a journalism student and am totally new to the world of Python. Right now, I am trying to convert the table on this site into a csv so I can add it to my database. Through lots of troubleshooting and some YouTube tutorials, I have come up with this:
import csv
import urllib.request
from bs4 import BeautifulSoup
f = open('dataoutput.csv', 'w', newline = '')
writer = csv.writer(f)
soup = BeautifulSoup(urllib.request.urlopen("https://www.townofchapelhill.org/town-hall/departments-services/planning-and-sustainability/gis-analytics/development-activity-report").read(), 'lxml')
tbody = soup('table', {"class":"tableData tablesorter tablesorter-blue hasFilters hasStickyHeaders"}) [0].find_all('tr')
for row in tbody:
cols = row.findChildren(recursive=False)
cols = [ele.text.strip() for ele in cols]
writer.writerow(cols)
print(cols)
f.close()
Right now, the code returns a csv, but it is empty. In the Mac OSX terminal, I get the following error:
as9934-pc:pythonstuff as9934$ python3 ./make.py
Traceback (most recent call last):
File "./make.py", line 8, in <module>
tbody = soup('table', {"class":"tableData tablesorter tablesorter-blue hasFilters hasStickyHeaders"}) [0].find_all('tr')
IndexError: list index out of range
The only number I specify is [0] so I'm confused rn.
Any thoughts?