I am using BeautifulSoup to parse data, and now I want to save it to a csv file. I am able to create a csv file; however, when I open the file it is blank. What should I write for writing to a csv file?
Script:
university = {}
for x in soup.find_all('p'):
name_tag = x.find('strong')
if name_tag != None:
name = name_tag.text
t = x.text
m = re.findall('\$([0-9]*)', t)
if m != []:
print(name +', ' + m[0])
Part of output:
Harvard University:, 400
Stanford University:, 400
Stanford University:, 400
Writing to a csv file:
import csv
with open ('gifts.csv', 'w', encoding="utf-8") as file:
writer=csv.writer(file)
for row in university:
writer.writerow(row)
You didn't add anything to your variable university
, change your code to :
import csv
university = []
for x in soup.find_all('p'):
name_tag = x.find('strong')
if name_tag != None:
name = name_tag.text
t = x.text
m = re.findall('\$([0-9]*)', t)
if m != []:
university.append([name +', ' + str(m[0]]) # append to variable university
with open('gifts.csv', 'w') as f:
writer = csv.writer(f)
for row in university:
writer.writerow(row)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.