如何显示数据的一个字一个单元,而不是一个字符一个细胞在csv_file?

时间:2019-02-01 12:37:25

标签: python csv

我练习从网站抓取数据。 这是网站: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()

1 个答案:

答案 0 :(得分:0)

您正在使用写行,如果要在单行中写入列表,则需要写多行,请参见下面的示例

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()