希望在这里得到帮助。我正在尝试在 MLS 的 FB Ref 上抓取第二个球员进球和射门创造统计数据表,但我的脚本引入了第一个球队统计数据表。有人可以帮忙吗?代码如下。
网址:https://fbref.com/en/comps/22/stats/Major-League-Soccer-Stats
# libraries
import pandas as pd
# fbref table link
url_df = 'https://fbref.com/en/comps/22/gca/Major-League-Soccer-Stats'
df = pd.read_html(url_df)
df
你需要在这里多努力一点。您所查找的表格实际上位于静态页面的注释中。所以简单地使用
pd.read_html()
不会为你带来它。
但是你可以手动提取相关评论然后解析它。
import requests
from bs4 import BeautifulSoup, Comment
import pandas as pd
from io import StringIO
url = 'https://fbref.com/en/comps/22/gca/Major-League-Soccer-Stats'
response = requests.get(url)
html_content = response.text
soup = BeautifulSoup(html_content, 'html.parser')
comments = soup.find_all(string=lambda text: isinstance(text, Comment))
for comment in comments:
# Check if the comment contains the target <div>.
if 'div_stats_gca' in comment:
# Parse the comment as HTML and extract target <div>.
div = BeautifulSoup(comment, 'html.parser').find(id='div_stats_gca')
df = pd.read_html(StringIO(str(div)))[0]
print(df.iloc[:, :6])
else:
print("Unable to find table.")
仅打印前七列,但可以确认它们都在那里。
这些是我正在使用的软件包:
lxml==5.2.2
pandas==2.2.2
beautifulsoup4==4.12.3
requests==2.31.0