首页 > 解决方案 > 为什么 writerow 不分离这些列表元素?

问题描述

我正在尝试抓取一个 Wikipedia 表格,但每次运行此代码时,excel 文件都不会按应有的方式分隔值,而是将行放在单元格中,而当它应该将年份、获胜者等分隔在不同的列中时。

我尝试通过在 writerow() 中直接使用列表运行它来测试它,结果是一样的。

url = "https://en.wikipedia.org/wiki/List_of_FIFA_World_Cup_finals"
html = urlopen("https://en.wikipedia.org/wiki/List_of_FIFA_World_Cup_finals")
wiki_bs_obj = BeautifulSoup(html, "html.parser")
table = wiki_bs_obj.find_all("table", {"class": re.compile(r"^wikitable")})[1]
rows = table.find_all("tr")
csv_file = open(r"C:\Users\odeig\Desktop\Scraped data\Football_cups.csv", "w", newline="")
writer = csv.writer(csv_file, dialect="excel")
try:
    csv_rows = []
    for row in rows:
        csv_row = []
        for cell in row.find_all(["td", "th"]):
            if cell.get_text().strip() != "":
                csv_row.append(cell.get_text().strip())
        csv_rows.append(csv_row)
    writer.writerows(csv_rows)
finally:
    csv_file.close()

链接中是我运行此代码时得到的 excel 输出的图片。[1]:https ://i.stack.imgur.com/KN3Cz.png

关于最小可重现示例,我将其放在下面,问题仍然存在,当在 excel 中打开它时,它仍然将行放在一个单元格中。

data = ["This", "Is", "A", "Test"]
csv_file_test = open("test.csv", "w", newline="")
writer_test = csv.writer(csv_file_test)
writer_test.writerow(data)

标签: pythoncsvweb-scraping

解决方案


从 Libre Office 或 Google 电子表格打开 csv 文件时,您的输出很好。

证明在此处输入图像描述

我认为问题在于excel如何导入这个文件。检查Excel设置,我会先寻找分隔符。


推荐阅读