【问题标题】:how to put this distorted data into the csv file, in the table format如何将这些扭曲的数据以表格格式放入 csv 文件中
【发布时间】:2020-11-09 13:42:10
【问题描述】:

请在下面找到我用来以表格格式将失真数据放入 CSV 文件的代码:

import requests
from bs4 import BeautifulSoup
import csv

f = open('moneyControl-bonus','w' , newline = '')
writer = csv.writer(f)

f2 = open('moneyControl-dividend','w' , newline = '')
writer2 = csv.writer(f2)

url = 'https://www.moneycontrol.com/stocks/marketinfo/upcoming_actions/home.html'

headers = {'user-agent':'Mozilla/5.0'}
response = requests.get(url,headers)

soup = BeautifulSoup(response.content,'lxml')
div = soup.find_all('div',class_='tbldata36 PT10')[0]

for table in div.find_all('table'):
    for row in table.find_all('tr'):
         writer.writerow[row]

    
div2 = soup.find_all('div',class_='tbldata36 PT20')[0]

for table2 in soup.find_all('table'):
     for row2 in table2.find_all('tr'):
            writer2.writerow[row2]

【问题讨论】:

  • 你能正确缩进你的代码吗?
  • 请添加更多上下文,例如数据的样子,以便我们尽可能准确地重现。

标签: python beautifulsoup urllib


【解决方案1】:

您是否尝试过使用pandas?这是用于编写 csv 格式的默认库。

# pip install pandas
import pandas as pd

您可以通过传递列表列表或字典来写入 CSV 文件。

df = pd.DataFrame({'col1':[1,2,3,4],'col2':['a','b','c','d']})
df = pd.DataFrame([[1,2,3,4],['a','b','c','d']],columns=['col1','col2'])

df.to_csv(path_and_name_of_file)

您可以使用多种不同的格式,例如 Excel、表格、文本、json 等。

请看official DataFrame Documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2022-07-11
    • 2012-07-17
    • 1970-01-01
    • 2015-04-28
    相关资源
    最近更新 更多