本文目录导读:

在Python中查看两队的历史交锋记录,通常需要根据数据来源选择不同的方法,以下是几种常见场景的解决方案:
使用预定义的数据结构(最简单)
如果你有静态数据(如CSV或硬编码列表),直接用Pandas处理:
import pandas as pd
# 示例数据:历史交锋记录
data = {
'日期': ['2023-05-01', '2023-10-15', '2024-03-20'],
'主队': ['曼联', '利物浦', '阿森纳'],
'客队': ['利物浦', '阿森纳', '曼联'],
'主队进球': [2, 1, 3],
'客队进球': [1, 2, 2],
'比赛性质': ['英超', '英超', '足总杯']
}
df = pd.DataFrame(data)
def get_head_to_head(team1, team2, df):
"""获取两队历史交锋记录"""
# 筛选两队相关的所有比赛(无论主客)
matches = df[
((df['主队'] == team1) & (df['客队'] == team2)) |
((df['主队'] == team2) & (df['客队'] == team1))
]
return matches
# 查看曼联 vs 利物浦
result = get_head_to_head('曼联', '利物浦', df)
print(result)
从API获取数据(如足球数据API)
使用requests库调用公开API:
import requests
def get_head_to_head_api(team1_id, team2_id, api_key):
"""从API获取交锋记录(示例:api-football)"""
url = "https://v3.football.api-sports.io/fixtures/headtohead"
params = {
'h2h': f"{team1_id}-{team2_id}",
'last': 10 # 最近10场
}
headers = {
'x-apisports-key': api_key
}
response = requests.get(url, params=params, headers=headers)
if response.status_code == 200:
return response.json()['response']
else:
return []
# 使用示例(需要有效API key)
# fixtures = get_head_to_head_api(33, 34, 'your_api_key')
从网页爬取(如维基百科)
使用BeautifulSoup解析公开网页:
from bs4 import BeautifulSoup
import requests
def scrape_head_to_head(team1, team2):
"""从维基百科或其他网站抓取交锋记录"""
# 示例:构造维基百科URL
url = f"https://en.wikipedia.org/wiki/{team1}_F.C.–{team2}_F.C._rivalry"
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
# 解析表格数据
# 注意:具体解析逻辑需根据网页结构定制
# 这里仅给出框架
return soup
return None
# 使用示例(需根据实际网页调整)
# page = scrape_head_to_head("Manchester United", "Liverpool")
使用现成的体育数据包
安装football-data-api等库:
pip install football-data-api
from football_data_api import FootballData
# 或者使用 other libraries like `soccerdata`
# 示例(伪代码,实际API可能不同)
api = FootballData('your_api_key')
matches = api.get_head_to_head('Manchester United', 'Liverpool')
| 方法 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
| Pandas | 本地数据 | 快速、无依赖 | 数据需自行维护 |
| API | 实时数据 | 数据最新 | 需要API key、有限流 |
| 爬虫 | 公开数据 | 免费详细 | 解析复杂、可能被封 |
| 数据包 | 快速开发 | 封装好 | 依赖特定库 |
建议:先尝试本地数据或API,避免爬虫带来的法律和稳定性风险,实际项目中通常会结合多种数据源,并用Pandas统一处理格式。