首页 > 解决方案 > 网页抓取 - 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 文件总是空白

标签: pythoncsvweb-scrapingbeautifulsoupexport-to-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)

推荐阅读