gpt4 book ai didi

python - 将 python 列表值写入 csv 文件

转载 作者:行者123 更新时间:2023-11-30 22:34:20 25 4
gpt4 key购买 nike

我正在尝试将生成的列表导出到 csv 文件,其中网站表中的每一行对应于文件中的新行,并且每个值都位于单独的单元格中,例如:

NAME.....ICO DATE....ICO PRICE....CURR. PRICE....24 HR ROI Stratis.....06/20/16.......$0.007...........$7.480................+38.80%

当前输出如下所示:

['Patientory\n05/31/17\n$0.104\n$0.274\n+46.11%\n+25.54%\nN/A']

import csv
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait

csvrows = []

def get_css_sel(selector):
posts = browser.find_elements_by_css_selector(selector)
for post in posts:
print(post.text)
csvrows.append([post.text])

browser = webdriver.Chrome(executable_path=r'C:\Scrapers\chromedriver.exe')
browser.get("https://icostats.com")
wait(browser, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#app > div > div.container-0-16 > div.table-0-20 > div.tbody-0-21 > div:nth-child(2) > div:nth-child(8)")))

get_css_sel("#app > div > div.container-0-16 > div.table-0-20 > div.tableheader-0-50") #fetch header of table
get_css_sel("#app > div > div.container-0-16 > div.table-0-20 > div.tbody-0-21 > div") #fetch rows of table

def create_csv(thelist):
with open('ICO.csv', 'w') as myfile:
for i in thelist:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow([i])

create_csv(csvrows)

最佳答案

get_css_sel() 中,每个 post.text 包含由换行符分隔的行文本 \n - 与输出示例相同。因此,附加 [post.text] 会附加一个列表,其中包含整行的单个项目。将其更改为:

csvrows.append(post.text.split('\n'))  # remove the extra list brackets
# since split returns a list.

例如:

>>> y = 'Patientory\n05/31/17\n$0.104\n$0.274\n+46.11%\n+25.54%\nN/A'
>>> y.split('\n')
['Patientory', '05/31/17', '$0.104', '$0.274', '+46.11%', '+25.54%', 'N/A']

此外,在写入循环中,您不应为每一行重新创建 csv.writer,只需在循环 thelist 之前执行一次即可。

由于您在 csvrows 中拥有所需的所有行,因此您可以使用 csvwriter.writerows直接。

def create_csv(thelist):
with open('ICO.csv', 'w') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerows(thelist)

关于python - 将 python 列表值写入 csv 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44877032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com