我对网页抓取有点陌生,想在 Python 中使用 BeautifulSoup 抓取一些 HTML 表格。该网页是https://fbref.com/en/comps/9/keepers/Premier-League-Stats。正如您将看到的,有两个表“Squad Goalkeeping”和“Player Goalkeeping”。
使用以下代码,我可以捕获两个表。
from bs4 import BeautifulSoup
import requests
import pandas as pd
import re
url = 'https://fbref.com/en/comps/9/keepers/Premier-League-Stats'
html_content = requests.get(url).text
bs = BeautifulSoup(html_content,"lxml")
gk_stats = bs.find_all("div",attrs={"class":"table_wrapper"})
gk_stats 包含 2 个元素“Squad Goalkeeping”和“Player Goalkeeping”,我可以分别通过索引 gk_stats[0] 和 gk_stats[1] 来查看它们。但是,当我尝试在“Player Goalkeeping”中找到“tr”标签时,它给了我一个空列表。
gk_stats[1].find_all("tr")
任何人都可以向我解释为什么即使我将它作为 BeautifulSoup 元素也无法提取表格?当我在 Chrome 浏览器中检查元素时,我也可以看到表格。
我可以使用相同的命令提取“Squad Goalkeeping”表,但索引为 0 gk_stats[0].find_all("tr")
提前致谢。
问题是表被注释了。快速修复是从 html 代码中删除<!--
和-->
。此外,您可以使用read_html
(不需要 BeautifulSoup)将html 表直接加载到 Pandas 中:
import requests
import pandas as pd
url = 'https://fbref.com/en/comps/9/keepers/Premier-League-Stats'
html_content = requests.get(url).text.replace('<!--', '').replace('-->', '')
df = pd.read_html(html_content)
read_html
将返回表作为dataframes,可与被访问的列表df[0]
,df[1]
等球员的门将是df[2]
。让我们删除顶部标题行和中间表格标题行:
df[2].columns = df[2].columns.droplevel(0) # drop top header row
df[2] = df[2][df[2]['Rk'].ne('Rk')].reset_index() # remove mid-table header rows
输出df[2]
:
索引 | Rk | 播放器 | 民族 | 位置 | 小队 | 年龄 | 出生 | 议员 | 开始 | 最小 | 90年代 | 遗传算法 | GA90 | 下 | 保存 | 节省% | 宽 | D | 升 | 计算机科学 | CS% | 帕克特 | PKA | PKsv | PKm | 节省% | 比赛 | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 0 | 1 | 阿德里安 | 是ESP | GK | 利物浦 | 34-068 | 1987年 | 3 | 3 | 270 | 3 | 9 | 3 | 19 | 10 | 52.6 | 1 | 1 | 1 | 1 | 33.3 | 0 | 0 | 0 | 0 | 在 | 比赛 |
1 | 1 | 2 | 鲁纳尔亚历克斯鲁纳尔松 | 是ISL | GK | 阿森纳 | 26-022 | 1995年 | 1 | 0 | 16 | 0.2 | 0 | 0 | 2 | 2 | 100 | 0 | 0 | 0 | 0 | 在 | 0 | 0 | 0 | 0 | 在 | 比赛 |
2 | 2 | 3 | 阿利松 | br 文胸 | GK | 利物浦 | 28-161 | 1992年 | 23 | 23 | 2070 | 23 | 26 | 1.13 | 73 | 50 | 69.9 | 10 | 6 | 7 | 5 | 21.7 | 8 | 4 | 1 | 3 | 20 | 比赛 |
3 | 3 | 4 | 阿方斯·阿雷奥拉 | FRA | GK | 富勒姆 | 28-013 | 1993年 | 27 | 27 | 2430 | 27 | 30 | 1.11 | 113 | 88 | 77.9 | 5 | 11 | 11 | 9 | 33.3 | 5 | 5 | 0 | 0 | 0 | 比赛 |
4 | 4 | 5 | 凯帕阿里扎巴拉加 | 是ESP | GK | 切尔西 | 26-160 | 1994年 | 4 | 4 | 360 | 4 | 6 | 1.5 | 18 | 12 | 66.7 | 2 | 1 | 1 | 1 | 25 | 0 | 0 | 0 | 0 | 在 | 比赛 |
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句