使用 Python 在 CSV 文件中编写完全相同的内容

Posted

技术标签:

【中文标题】使用 Python 在 CSV 文件中编写完全相同的内容【英文标题】:Writing the exact same thing in CSV file using Python 【发布时间】:2018-09-07 00:59:08 【问题描述】:

我在为网络抓取项目编写 CSV 程序时遇到了问题。

我得到了如下格式的数据:

table = 
    "UR": url,
    "DC": desc,
    "PR": price,
    "PU": picture,
    "SN": seller_name,
    "SU": seller_url

我从分析 html 页面并返回此表的循环中得到。 基本上这张表还可以,每次循环都会变。

现在的事情是,当我想把从那个循环中得到的每个表写入我的 CSV 文件时,它只会一遍又一遍地写同样的东西。 唯一编写的元素是我使用循环获得的第一个元素,它写了大约 1000 万次而不是大约 45 次(每页文章数)

我尝试使用库“csv”然后使用 pandas。

这是我的循环:

if os.path.isfile(file_path) is False:
    open(file_path, 'a').close()
file = open(file_path, "a", encoding = "utf-8")

i = 1
while True:
    final_url = website + brand_formatted + "+handbags/?p=" + str(i)
    request = requests.get(final_url)
    soup = BeautifulSoup(request.content, "html.parser")
    articles = soup.find_all("div", "class": "dui-card searchresultitem")
    for article in articles:
        table = scrap_it(article)
        write_to_csv(table, file)
    if i == nb_page:
        break
    i += 1
file.close()

这里是我写入 csv 文件的方法:

def write_to_csv(table, file):
import csv

writer = csv.writer(file, delimiter = " ")
writer.writerow(table["UR"])
writer.writerow(table["DC"])
writer.writerow(table["PR"])
writer.writerow(table["PU"])
writer.writerow(table["SN"])
writer.writerow(table["SU"])

我在编写 CSV 文件和 Python 方面非常陌生,但我不知道为什么这不起作用。我遵循了许多指南,并获得了或多或少相同的编写 csv 文件的代码。

编辑:这是我的 csv 文件的 img 输出

你可以看到每个元素都是一样的,即使我的表发生了变化

编辑:我通过为我废弃的每篇文章制作一个文件来解决我的问题。这是很多文件,但显然对我的项目来说没问题。

【问题讨论】:

分享错误? 我编辑帖子 我认为函数writer.writerow是用来写一行的,而不是一个字段。 【参考方案1】:

这可能是您想要的解决方案

import csv

fieldnames = ['UR', 'DC', 'PR', 'PU', 'SN', 'SU']    

def write_to_csv(table, file):
    writer = csv.DictWriter(file, fieldnames=fieldnames)
    writer.writerow(table)

参考:https://docs.python.org/3/library/csv.html

【讨论】:

不是这样,但我给你一个赞成票,因为它的格式比我的好!谢谢!

以上是关于使用 Python 在 CSV 文件中编写完全相同的内容的主要内容,如果未能解决你的问题,请参考以下文章

python--csv文件读写

CSV 应该返回字符串,而不是字节错误

如何使用 Python 中的 argparse 和 csv 库编写文件?

在 Python 中异步编写 CSV 文件

在 python 2 或 python 3 中编写 csv 文件的便携方式

在 Python 中编写适用于 Windows 中的 Python 2.7+ 和 Python 3.3+ 的 .CSV 文件