python - 网页抓取 - Python;写入 CSV
问题描述
我正在尝试从网站写入数据。当新的数据块列在排名中时,数据以 HTML 表格的形式列出,标签为 '' 列表,关于排名中元素的每个描述性项目为 ''。该列表是前 500 台计算机的排名,列出 1-100,每个 1、2、3、4 等项目用“”列出,计算机的每个特性都用“”列出(它的存储、最大功率等) )。
这是我的代码:
# read the data from a URL
url = requests.get("https://www.top500.org/list/2018/06/")
url.status_code
url.content
# parse the URL using Beauriful Soup
soup = BeautifulSoup(url.content, 'html.parser')
filename = "computerRank10.csv"
f = open(filename,"w")
headers = "Rank, Site, System, Cores, RMax, RPeak, Power\n"
f.write(headers)
for record in soup.findAll('tr'):
# start building the record with an empty string
tbltxt = ""
tbltxt = tbltxt + data.text + ";"
tbltxt = tbltxt.replace('\n', ' ')
tbltxt = tbltxt.replace(',', '')
# f.write(tbltxt[0:-1] + '\n')
f.write(tbltxt + '\n')
f.close()
我什么也没得到,我的 CSV 文件总是空白
解决方案
您应该csv
在 Python 标准库中使用模块。
这是一个更简单的解决方案:
import requests
import csv
from bs4 import BeautifulSoup as bs
url = requests.get("https://www.top500.org/list/2018/06")
soup = bs(url.content, 'html.parser')
filename = "computerRank10.csv"
csv_writer = csv.writer(open(filename, 'w'))
for tr in soup.find_all("tr"):
data = []
# for headers ( entered only once - the first time - )
for th in tr.find_all("th"):
data.append(th.text)
if data:
print("Inserting headers : {}".format(','.join(data)))
csv_writer.writerow(data)
continue
for td in tr.find_all("td"):
if td.a:
data.append(td.a.text.strip())
else:
data.append(td.text.strip())
if data:
print("Inserting data: {}".format(','.join(data)))
csv_writer.writerow(data)
推荐阅读
- django - Django 远程服务器正在运行,但我无法连接到本地 Web 浏览器中的管理界面
- python - 为什么在使用函数时只打印最后一个元素
- php - mcrypt_generic 是否容易受到 padding oracle 攻击?
- math - RYYB 图像的 RYB 和 RGB 颜色空间之间的转换
- arduino - 当我在 python 中使用 serial.tools.list_ports 检查串口时,为什么 Arduino 会重置?
- .net-core - EF Core 3.1 查询导致 InvalidOperationException Lambda 表达式在 Include 中使用无效
- reactjs - 如何在 React 中测试代码风格和标准?
- python - 如何在不实际键入变量的情况下删除多个变量?
- python - 从具有重复数据的行中创建列中的数组
- heroku - 在heroku上部署的MERN应用程序路径中的问题