【发布时间】:2020-05-12 19:46:19
【问题描述】:
我对 python 和 BeautifulSoup 很陌生。我编写了以下代码来调用网站:https://www.baseball-reference.com/leagues/MLB-standings.shtml,目的是抓取底部名为“MLB 详细排名”的表格并导出为 CSV 文件。我的代码成功创建了一个 CSV 文件,但提取了错误的数据表,并且缺少包含团队名称的第一列。我的代码将“东区”表格拉到顶部(不包括第一列),而不是我的目标表格,底部有完整的“MLB 详细排名”表格。
想知道是否有一种简单的方法可以将 MLB 详细排名表拉到底部。当我检查页面时,我试图提取的特定表的 ID 是:“expanded_standings_overall”。我需要在我的代码中引用它吗?或者,将不胜感激任何其他重新编写代码以提取正确表的指导。再说一次,我很新,正在努力学习。
import requests
import csv
import datetime
from bs4 import BeautifulSoup
# static urls
season = datetime.datetime.now().year
URL = "https://www.baseball-reference.com/leagues/MLB-standings.shtml".format(season=season)
# request the data
batting_html = requests.get(URL).text
def parse_array_from_fangraphs_html(input_html, out_file_name):
"""
Take a HTML stats page from fangraphs and parse it out to a CSV file.
"""
# parse input
soup = BeautifulSoup(input_html, "lxml")
table = soup.find("table", class_=["sortable,", "stats_table", "now_sortable"])
# get headers
headers_html = table.find("thead").find_all("th")
headers = []
for header in headers_html:
headers.append(header.text)
print(headers)
# get rows
rows = []
rows_html = table.find_all("tr")
for row in rows_html:
row_data = []
for cell in row.find_all("td"):
row_data.append(cell.text)
rows.append(row_data)
# write to CSV file
with open(out_file_name, "w") as out_file:
writer = csv.writer(out_file)
writer.writerow(headers)
writer.writerows(rows)
parse_array_from_fangraphs_html(batting_html, 'BBRefTest.csv')
【问题讨论】:
-
请求的答案只包含 6 个表。看来您需要使用标题和/或会话才能获得完整答案。
-
仅供参考,有一个相当流行的 Python 库可以用来抓取balloon-reference.com github.com/jldbc/pybaseball
标签: python python-3.x beautifulsoup