我有一些用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


不幸的是,这段代码导致每个单独的字符或字母都有自己的单元格:

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

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

最佳答案

cell.text是字符串,但是writerow需要可迭代的数据,因此它可以将每个元素写入其自己的单元格。自从传递列表以来,每个字符都被视为一个单独的元素,并被写入单独的单元格中。

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

writer.writerow([cell.text])

关于python - 写入CSV会导致每个字母都有自己的单元格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47138162/

10-11 22:36
查看更多