Python.csv writer将数据放在错误的行(python3.7)奇怪的格式

2024-04-19 22:33:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用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的初学者,所以如果这是一个愚蠢的问题,我会提前道歉。不过,我非常感谢你在这个问题上的任何帮助。谢谢您!你知道吗


Tags: csvfromimportdatarawpagefinditem
2条回答

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

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)

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

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

当然,您也可以使用CSV模块。你知道吗

如果你提供了一个例子页面,你想刮以及领域的兴趣,这将有助于回答你的问题,这是相当模糊的

相关问题 更多 >