将抓取的数据导入 CSV

Import Data from scraping into CSV

我正在使用 pycharm 和 Python 3.7.

我想在 csv 中写入数据,但我的代码在文件中只写入了我数据的第一行...有人知道为什么吗?

这是我的代码:

from pytrends.request import TrendReq
import csv


 pytrend = TrendReq()
 pytrend.build_payload(kw_list=['auto model A', 
 'auto model C'])


# Interest Over Time
interest_over_time_df = pytrend.interest_over_time()
print(interest_over_time_df.head(100))



writer=csv.writer(open("C:\Users\
Desktop\Data\c.csv", 'w', encoding='utf-8'))

writer.writerow(interest_over_time_df)

尝试使用 pandas、

import pandas as pd
interest_over_time_df.to_csv("file.csv")

有一次我遇到了同样的问题,解决方法如下:

with open("file.csv",  "rb", encoding="utf-8) as fh:

具体细节:

r = read mode
b =  mode specifier in the open() states that the file shall be treated as binary, 
so contents will remain a bytes. No decoding attempt will happen this way.

正如我们所知,python 尝试将字节数组(假定为 utf-8 编码字符串的字节)转换为 unicode 字符串 (str)。这个过程当然是按照utf-8规则进行解码。当它尝试这样做时,它遇到了 utf-8 编码字符串中不允许的字节序列(即位置 0 处的 0xff)。

您可以尝试类似的方法:

import csv
with open(<path to output_csv>, "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter=',')
    for line in interest_over_time_df:
        writer.writerow(line)

在此处阅读更多内容:https://www.pythonforbeginners.com/files/with-statement-in-python

需要循环遍历数据,逐行写入