首页 > 解决方案 > 将 MLB 网站上的游戏统计表读入美丽的汤

问题描述

我正在尝试从 MLB 球员网站(https://www.mlb.com/player/charlie-morton-450203?stats=gamelogs-r-pitching-mlb&year=2019)中抓取/读取 Game Stats 表。我似乎无法找到/捕获类名。当我在 chrome 中“检查 HTML”时,我可以看到类名,但美丽的汤似乎找不到。

是否有一些解决方法/技巧可以正确输入?

from bs4 import BeautifulSoup
import requests

page = requests.get('https://www.mlb.com/player/charlie-morton-450203?stats=gamelogs-r-pitching-mlb&year=2019')

soup = BeautifulSoup(page.text, "html.parser")
body = soup.find('body')

table = body.findAll('div', {'class':'gamelogs-table'})
print(table)

标签: pythonbeautifulsoup

解决方案


数据通过 AJAX 加载。对于正确的数据源,您需要通过例如 Firefox 中的开发者控制台找到 URL。此脚本打印 player 的 JSON 数据450203

import requests
import json

url = 'https://statsapi.mlb.com/api/v1/people/450203/stats?stats=gameLog'
data = requests.get(url).json()

print(json.dumps(data, indent=4))

推荐阅读