我想从网站中提取数据,然后将其显示在我的网页上

时间:2020-04-23 06:27:50

标签: python web-scraping

首先,我必须提取它并将其保存在CSV文件中。这是我的代码

import requests
from bs4 import BeautifulSoup
import csv

result = requests.get("https://www.health.govt.nz/our-work/diseases-and-conditions/covid-19-novel-coronavirus/covid-19-current-situation/covid-19-current-cases")
src = result.content
soup = BeautifulSoup(src,'lxml')

cov19_table = soup.find("table", attrs={"class": "table-style-two"})
cov19_table_data = cov19_table.find_all("tbody")

headings = []
# gives me headings 
for th in cov19_table_data[0].find_all("th"): #3rows
    headings.append(th.text.replace('\n',' ').strip())
#print(headings)

t_data = []
for td in cov19_table_data[0].find_all("td"):
    t_data.append(td.text.strip())
print(t_data)

with open('data.csv', 'w', newline="") as new_file:
  csv_writer = csv.writer(new_file)
  csv_writer.writerows(t_data)

每当我打开data.csv文件时,我都会得到此数据

This is how it saving

原始表如下所示: This is what I want to extract

2 个答案:

答案 0 :(得分:0)

您的t_data只是一列列-您只有一行-阅读writerows-它需要一列行,每行都是一列列。

使用

with open('data.csv', 'w', newline="") as new_file:
  csv_writer = csv.writer(new_file)
  csv_writer.writerows( [t_data] )  # fix here

最好不要泄漏数据并将其添加到页面中而不归属源。在该链接上添加链接将使人们可以阅读更多有关它的信息。

如果文本文件中的偶尔引用使您烦恼,则可能还需要使用标题和其他分隔符。它必须立即引用所有包含','的字符串:

with open('data.csv', 'w', newline="") as new_file:
    csv_writer = csv.writer(new_file, delimiter='|')
    csv_writer.writerow(headings)
    csv_writer.writerows([t_data])

获得:

新西兰的确诊病例数|可能的病例数|确诊和可能的病例数|目前在医院的病例数|已康复的病例数|死亡人数
1,112 | -1 | 339 | 1 | 1,451 | 0 | 8 | -3 | 1,065 | 29 | 16 | 2

答案 1 :(得分:-1)

在处理生成的数据时,您需要从字符串中删除,,然后将其转换为整数,然后再添加它。

value = td.text.strip().replace(',', '')
t_data.append(int(value))

由此,事情变得简单了一些,新的t_data看起来像:

[1112, -1, 339, 1, 1451, 0, 8, -3, 1065, 29, 16, 2]

我想您现在可以很容易地弄清文字。另一件事是csv文件,它没有标题..也可能会将标题也写入其中。

相关问题