我对此很陌生,似乎无法使它正确地出口。
# select document
with open('scrape1.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')
# create/name csv
with open('speechengine_report.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['computer', 'usagedata'])
# tell bs4 to only look at x tags with a class of y
for licensedata in soup.find_all('div', class_='licensedata'):
# scrape pc id
computer = licensedata.p.b.text
print(computer)
# scrape usage stats for each id
for usagedata in licensedata.find_all('td'):
# minutes = usagedata.table.tbody
print(usagedata.text)
# blank line
print()
# writer.writerow([computer, usagedata])
csv_file.close()
发布于 2020-12-11 23:05:47
要将数据写入csv文件的其余代码应该在with块中。另外,您也不需要csv_file.close(),因为它为您处理这个问题。试试下面的代码。读取python中的文件处理
with open('scrape1.html') as html_file:
soup = BeautifulSoup(html_file, 'lxml')
# create/name csv
with open('speechengine_report.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(['computer', 'usagedata'])
# tell bs4 to only look at x tags with a class of y
for licensedata in soup.find_all('div', class_='licensedata'):
# scrape pc id
computer = licensedata.p.b.text
print(computer)
# scrape usage stats for each id
for usagedata in licensedata.find_all('td'):
# minutes = usagedata.table.tbody
print(usagedata.text)
# blank line
print()
# writer.writerow([computer, usagedata])
https://stackoverflow.com/questions/65259370
复制相似问题