写入 CSV 会导致每个字母都有自己的单元格

Writing to CSV results in each letter having its own cell

我有一些代码可以用 BeautifulSoup 解析 HTML 并打印代码。 Here is the source code(如果有兴趣链接要点):

import csv
import requests
from bs4 import BeautifulSoup
import lxml

r = requests.post('https://opir.fiu.edu/instructor_evals/instr_eval_result.asp', data={'Term': '1175', 'Coll': 'CBADM'})
soup = BeautifulSoup(r.text, "lxml")

tables = soup.find_all('table')
print(tables)



print(tables)

我的代码在导出为 CSV 之前的输出如下所示:

 Question   No Response Excellent   Very Good     
  Good   Fair    Poor   
  Description of course objectives and assignments  
  0.0%  76.1%   17.4%   6.5%    0.0%    
  0.0%  
  Communication of ideas and information    0.0%    
  78.3% 17.4%   4.3%    0.0%    0.0%    

我非常喜欢这个输出,想将它导出为 CSV,所以我添加了以下内容:

writer = csv.writer(open("C:\Temp\output_file.csv", 'w'))

for table in tables:
rows = table.find_all("tr")
for row in rows:
    cells = row.find_all("td")
    if len(cells) == 7:  # this filters out rows with 'Term', 'Instructor Name' etc.
        for cell in cells:
            print(cell.text + "\t", end="") 
            writer.writerow(cell.text)
        print("")  # newline after each row
print("-------------")  # table delimiter

不幸的是,此代码导致每个唯一的字符或字母都有自己的单元格:

所以我的问题是:如何修复此代码,以便它正确地将输出导出到 CSV 文件,而不为每个字符添加一个新单元格?我不确定为什么要这样做。它似乎也只导出第一个 table,并忽略代码中的所有其他数据。

cell.text 是一个字符串,但是 writerow 需要一个可迭代的数据,所以它可以将每个元素写入它自己的单元格。由于您传递了一个列表,每个字符都被视为一个单独的元素并写入单独的单元格。

您必须将 [] 包裹在字符串周围才能使其正常工作,因此您传递的是一个字符串列表:

writer.writerow([cell.text])