把MLB网站上的游戏统计表读入靓汤

2024-04-28 23:12:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从MLB玩家网站(https://www.mlb.com/player/charlie-morton-450203?stats=gamelogs-r-pitching-mlb&year=2019)中抓取/读取游戏统计表。我似乎找不到/捕捉不到类名。我在chrome中“检查HTML”时可以看到类名,但是beautiful soup似乎找不到它。你知道吗

是否有一些解决方法/技巧来正确地将其导入?你知道吗

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)

Tags: httpscomwwwstatstablebodyyearmorton
2条回答

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

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))

如果您只想检索数据,我建议您在尝试检索网站之前先查找现有的api,如this。scraper很容易受到网站布局变化的影响。你知道吗

This是您可能感兴趣的reddit论坛。你知道吗

相关问题 更多 >