gpt4 book ai didi

python - 如何在 csv_file 中显示一个单词一个单元格而不是一个字符一个单元格的数据?

转载 作者:太空宇宙 更新时间:2023-11-03 21:18:47 25 4
gpt4 key购买 nike

我练习从网站上抓取数据。这是网站:https://delicious-fruit.com/ratings/full.php?q=ALL

我的主要目标是收集游戏名称、难度、评分、评分数,然后用csv保存文件。格式为一字一格,四字一换行。

当我尝试保存文件时,发生了问题。该文件在一个单元格中显示一个字符,而不是在一个单元格中显示一个单词。 result

我认为问题是“for 循环”的影响,但不知道解决它。你能给我一些建议吗?我将不胜感激。

我尝试使用另一个变量来存储数据并将其放入“writerows”函数中,但结果保持不变。

from bs4 import BeautifulSoup
import requests
import csv

source = requests.get('https://delicious-fruit.com/ratings/full.php?q=ALL').text
soup= BeautifulSoup(source, 'lxml')

with open ('cms_scrape.csv', 'w', errors='ignore') as csv_file:
writer = csv.writer(csv_file)
table = soup.find('tbody')
table_rows = table.find_all('tr')
for tr in table_rows:
td = tr.find_all('td')
writer.writerows([td[0].text, td[1].text, td[2].text, td[3].text])
csv_file.close()

最佳答案

您正在使用 writerows,它将写入多行,如果您想在单行中写入列表,您需要使用 writerow,请参阅下面的示例

from bs4 import BeautifulSoup
import requests
import csv

source = requests.get('https://delicious-fruit.com/ratings/full.php?q=ALL').text
soup= BeautifulSoup(source, 'lxml')

with open ('d:\\cms_scrape.csv', 'wb') as csv_file:
writer = csv.writer(csv_file)
table = soup.find('tbody')
table_rows = table.find_all('tr')
for tr in table_rows:
td = tr.find_all('td')
try:
texts = [str(td1.text).strip() for td1 in td]
writer.writerow(texts)
except Exception as e:
print "error while writing this row %s"%td
csv_file.close()

关于python - 如何在 csv_file 中显示一个单词一个单元格而不是一个字符一个单元格的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54479688/

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