我使用BeautifulSoup来解析数据,现在我想将它保存到csv文件中。我能够创建一个csv文件;但是,当我打开文件时,它是空白的。我应该写什么来写一个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 != []:
print(name +', ' + m[0])
部分输出:
Harvard University:, 400
Stanford University:, 400
Stanford University:, 400
写入csv文件:
import csv
with open ('gifts.csv', 'w', encoding="utf-8") as file:
writer=csv.writer(file)
for row in university:
writer.writerow(row)
答案 0 :(得分:1)
您没有向变量university
添加任何内容,请将代码更改为:
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)