Reputation: 197
I'm trying to save a table on this website > https://www.valuewalk.com/2019/01/top-10-most-obese-countries-oecd-who/
It does print out, but it doesn't save in a CSV. Can someone help out giving some advice?
from bs4 import BeautifulSoup
import csv
#Request webpage content
result = requests.get('https://www.valuewalk.com/2019/01/top-10-most-obese-countries-oecd-who/')
#Save content in var
src = result.content
#soupactivate
soup = BeautifulSoup(src,'lxml')
#look for table
tbl = soup.findAll('ol')
tbl2 = tbl[1]
#Get text out of table
tbltxt = tbl2.get_text()
#Open CSV
file = open('obesecountries.csv','w')
writer = csv.writer(file)
#Put data into csv
for row in tbltxt:
writer.writerow(row)
I found the HTML table I would like to get out of. I removed the HTML tags. It prints out but it doesn't save/write in CSV.
Upvotes: 0
Views: 46
Reputation: 964
#Open CSV
file = open('obesecountries.csv','w')
writer = csv.writer(file)
#look for table
tbl = soup.findAll('ol')
#Put data into csv
for row in tbl:
# get the text from the second item in the row
txt = [row[1].get_text()]
#Get text out of table
writer.writerow(txt)
Upvotes: 1
Reputation: 780798
tbltxt
is a string, not a list. You should be looping over the <li>
elements.
And the argument to writerow()
should be a list, not a string.
for li in tbl2.findAll('li'):
rowtext = li.get_text()
write.writerow([rowtext])
Upvotes: 2