python - 将一些表格内容写入文本文件时遇到问题
问题描述
我用 python 编写了一个脚本来从网页中获取一些表格内容,我的脚本可以相应地解析它们。但是,问题是我无法将它们写入文本文件。当我尝试编写时,脚本会抛出指向最后一行的错误TypeError: write() argument must be str, not list
。
我试过:
import requests
from bs4 import BeautifulSoup
url = "https://en.wikipedia.org/wiki/Comparison_of_Intel_processors"
res = requests.get(url)
soup = BeautifulSoup(res.text, "lxml")
with open("tabular_content.txt", "w", newline="", encoding="UTF-8") as outfile:
for items in soup.find("table",class_="wikitable").find_all("tr"):
data = [item.get_text(strip=True) for item in items.find_all(["th","td"])]
print(data)
outfile.write(data)
如何将表格数据写入文本文件?
解决方案
此脚本会将表格数据保存到'\t'
-separated csv 文件。
import requests
from bs4 import BeautifulSoup
url = "https://en.wikipedia.org/wiki/Comparison_of_Intel_processors"
res = requests.get(url)
soup = BeautifulSoup(res.text, "lxml")
with open("file.csv", "w", newline="", encoding="UTF-8") as outfile:
for items in soup.find("table",class_="wikitable").find_all("tr"):
data = [item.get_text(strip=True).replace('\n', ' ') for item in items.find_all(["th","td"])]
print(data)
outfile.write('\t'.join(data) + '\n')
LibreOffice 中的结果:
推荐阅读
- python - 在不阻塞的情况下延迟对 HTTP 请求的响应
- node.js - 使用 docker-compose 运行 nodejs 不起作用,但可以使用 docker run 命令
- selenium - 我在第一行遇到的在线词法错误或解析错误,我想在示例中使用多个数据并结合场景大纲
- java - System.currentTimeMillis() 与 Timestamp.valueOf(LocalDateTime.now(UTC)).getTime()
- php - 如何自定义标签短代码以仅适用于一种产品
- c++ - 从单独的文件中读取树
- r - R中finalfit包的奇怪输出回归表
- azure - 如何使用 PowerShell 获取 Azure 订阅的 TAG 值
- r - 如何在 R 中的所有观察中将李克特量表数据转换为数值?
- c++ - 使用 C++ 枚举(输入检查)