Python .csv编写器将数据放在错误的行(Python 3.7)奇怪的格式

时间:2019-03-14 16:36:31

标签: python python-3.x csv beautifulsoup

我正在尝试使用BeautifulSoup从网页中提取数据并将其格式化为.csv文件格式。我已经很成功地获取了页面中的数据,但是我不知道如何正确格式化文件。

我的问题是,如果我在第一列中有10个项目(带有标题的11行),则下一列中的数据将从我的第12行开始。 .csv最终看起来像是交错的(例如楼梯),

Field1,Field2,Field3
data1,,
data1,,
data1,,
,data2,
,data2,
,data2,
,,data3
,,data3
,,data3

显然,使用格式如下的.csv会容易得多

Field1,Field2,Field3
data1,data2,data3
data1,data2,data3
data1,data2,data3

我的代码如下:

import time
import requests
import csv
from bs4 import BeautifulSoup

# Time to wait between each item.
t = .010

# Create a csv file to write to.
f = open('filename.csv', 'w')
fieldnames = ('Field1','Field2')
writer = csv.DictWriter(f, fieldnames = fieldnames, lineterminator = '\n')
writer.writeheader()

# Define target page.
url = 'https://www.example.com'
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')

# Filter useful information from the page.
data_list = soup.find(class_='class0')
data_raw = data_list.find_all(class_='class1')
otherData_raw = otherData_list.find_all(class_='class2')

# Extract [data1] from html.
for data_location in data_raw:
    data_refine = data_location.find_all('a')

    for data_item in data_refine:
        field1 = data_item.contents[0]
        writer.writerow({'Field1':field1})
    time.sleep(t)

# Extract [data2] from html.
for otherData_location in otherData_raw:
    otherData_refine = otherData_location.find_all('a')

    for otherData_item in otherData_refine:
        field2 = otherData_item.contents[0]
        writer.writerow({'Field2':field2})
    time.sleep(t)

f.close()

我已经尝试了几种解决方案,但是没有任何运气。我是Python的初学者,所以如果这是一个愚蠢的问题,我会提前道歉。我将非常感谢您对此问题的任何帮助。谢谢!

2 个答案:

答案 0 :(得分:0)

我建议在输出任何内容之前先收集所有数据。如果您需要在一行中包含多个数据,请将它们全部添加到列表中,然后将其写入CSV,如下所示:

with open('csv.csv', 'w', encoding='utf-8') as f:
    for line in csv_data:
        f.write(','.join(line) + '\n')

您当然也可以使用CSV模块。

如果您提供了一个您希望抓取的示例页面以及感兴趣的字段,那么它将有助于回答您的问题,因为它是相当模糊的

答案 1 :(得分:0)

该代码每行写入一个单元格:

writer.writerow({'Field1':field1})

会写

foo,,  # Only Field1 column is populated

writer.writerow({'Field2':field2})

会写

,foo,  # Only Field2 column is popuplated

将所有列连续收集,然后再将其写入文件

row = {'Field1: 'foo', 'Field2': 'bar'...}
writer.writerow(row)