python - 为什么 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)
解决方案
推荐阅读
- forms - W/IInputConnectionWrapper:非活动 InputConnection 上的 getCursorCapsMode
- java - What is an Integer?
- eigen - 本征中的按行展平的外积
- android - 将 DJI UXSDK 集成到我的 Android Studio3.5 失败
- arrays - Julia 初始化一个与另一个大小相同的空数组的快速方法?
- webdeploy - Web 部署发布/包验证错误:$(MsDeployServiceUrl) 的属性值缺失或无效
- bash - 获取 bash 执行 bash 脚本的位置
- listview - 颤动中非动态容器小部件的水平轮播
- curl - 不以 root 身份运行时如何修复 curl 错误 (51)?
- initialization - 如何在 Blazor webassembly 应用程序启动时初始化变量?