首页 > 解决方案 > 如何将 BeautifulSoup 的输出保存为 csv?

问题描述

我是 python 的初学者,我正在尝试使用它从以下位置抓取数据: https ://www.spotrac.com/nfl/arizona-cardinals/sam-bradford-6510/cash-earnings/ (以及其他此类页面)

我真的只需要球员姓名(这里是 Sam Bradford),然后是每年年底的总现金值。所以基本上是一张带有年份和美元的表格。

我用beautifulsoup 来获得输出,并修改了一些代码,我在一个看起来像表格的东西中得到了一个终端输出。但我的最终目标是将其保存为 csv 或 xlsx,以便我可以将其移动到像 Stata 这样的程序中。理想情况下,我想为网站上的每个此类页面自动执行此过程。

我到目前为止的代码是:

from bs4 import BeautifulSoup
from bs4 import SoupStrainer
import urllib.request
import csv
import pandas as pd
import requests
from tabulate import tabulate

url = "https://www.spotrac.com/nfl/arizona-cardinals/sam-bradford-6510/cash-earnings/"

markup = urllib.request.urlopen(url).read()

soup = BeautifulSoup(markup, "lxml")

name_box = soup.title.text.strip()
#print(name_box)

earnings_table = soup.find('table', class_ = "earningstable")
#print(earnings_table.get_text())
rows = earnings_table.find_all('tr')
for row in rows:
    cols=row.find_all('td')
    cols=[x.text.strip() for x in cols]
    print(cols)

with open('test.csv', 'a') as csv_file:
    #writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    writer = csv.writer(open("/path/SamBradford.csv", 'w'))
    writer.writerow([name_box, cols])

这给了我一个 csv,但是工资数据都在一个列中,这没有帮助。

任何有关如何保存这个然后可能为网站上的其他页面自动化的帮助将不胜感激。

标签: pythonbeautifulsoup

解决方案


这是一个可能的解决方案:

from bs4 import BeautifulSoup
from bs4 import SoupStrainer
import urllib.request
import csv
import pandas as pd
import requests

url = "https://www.spotrac.com/nfl/arizona-cardinals/sam-bradford-6510/cash-earnings/"
markup = urllib.request.urlopen(url).read()
soup = BeautifulSoup(markup, "lxml")
name_box = soup.title.text.strip()
# I use for pandas for parse html tables to csv
# The problem that I found was your table have 2 tbody ...so I decided make a format
# 'find' will find the first tag
earnings_table = soup.find('table', class_ = "earningstable")
tbody = earnings_table.find('tbody')
thead = earnings_table.find('thead')
table='<table>'+str(thead)+str(tbody)+'</table>'
df = pd.read_html(str(table), flavor="bs4")[0]
df.to_csv('test.csv',index=False)

推荐阅读