首页 > 解决方案 > 如何通过网络抓取将表格数据从网站写入 CSV

问题描述

我是网络抓取的新手,我正在尝试在登录后从网站上抓取表格数据。我希望将第二列乘以 10。

目前该表正在写入 csv 但我真正想要的工作是将第二列乘以 10 并写入 csv

我尝试过的是:

r2=session.post("http://www.example.com")
soup = BeautifulSoup(r2.text, "html.parser")
        csvFile=open('Table.csv','w')
        output = csv.writer(csvFile)
        for table in soup.find_all('table')[5:]:
            for row in table.find_all('tr'):
                col = map(cell_text, row.find_all(re.compile('t[dh]')))
                output.writerow(col)
            output.writerow([])
        csvFile.close()

例如,如果我在网站上有一个包含数据的表格:

Time    Pressure   Mass     Temp

0.00    1.01       21       23.09
1.00    2.0908     21.1      10.07
2.0     2.8666     22.3      13.6
0.555   2.6545     2.4       32.56

The data for writing csv file should be:



0.00    10.1       21       23.09
1.00    20.908     21.1      10.07
2.0     28.666     22.3      13.6
0.555   26.545     2.4       32.56

怎么做?

标签: pythoncsvweb-scrapinghtml-tablebeautifulsoup

解决方案


它取决于元素的放置方式,在这里我有可以将其应用于 csv 的解决方案。

import pandas as pd
df = pd.read_csv("Table.csv")
df.Pressure = df.Pressure * 10
df.to_csv("Table_Updated.csv",index=False)
df.to_csv("DataExport.csv",index=False,header=False) # Store without header

推荐阅读