python - 使用 BeautifulSoup 从 transfermarkt 页面刮取数据
问题描述
我正在尝试使用 BeautifulSoup 从该页面中抓取表格并将其放入 DataFrame 中。目前我已经尝试过
from bs4 import BeautifulSoup
import requests
import pandas as pd
r = requests.get("https://www.transfermarkt.co.uk/laliga/legionaereeinsaetze/wettbewerb/ES1/saison_id/2020/altersklasse/alle/option/spiele/plus/1", headers= {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0"})
soup = BeautifulSoup(r.content, "html.parser")
results = soup.find_all("tbody")[1].find_all("a")
for result in results:
print(result.text)
我得到的结果是
Athletic
27
26
1
99.9 %
0.1 %
CA Osasuna
28
22
6
84.5 %
15.5 %
SD Huesca
27
20
7
82.7 %
17.3 %
...
我尝试使用print(result.text[0])对数据进行切片以尝试拆分结果,但尝试将其转换为 DataFrame 没有成功。还有其他方法可以做到这一点吗?
解决方案
首先找到该表并用于pd.read_html
解析表,因为str
它将作为列表返回并df
从中创建
results = soup.find("table",class_="items")
df=pd.read_html(str(results))[0]
df.drop(columns=['wappen',"% minutes foreign players"],inplace=True)
df.columns=['Club', 'Players used', 'Non-foreigners played',
'Used foreign players', '% minutes non-foreigners',
'% minutes foreign players']
推荐阅读
- python - 具有随机值的 Python DataFrames 查找
- android - 如何在 GridLayout 的第三行插入按钮?
- android - adb root 权限被拒绝
- swift - 可观察对象视图模型反复重新初始化 - 无限循环
- python - 没有端口转发的点对点套接字通信
- prometheus - 集成 Prometheus、Grafana 和 Azure
- linux - 命令替换:第 72 行:意外标记 `(' 附近的语法错误
- keycloak - 如何通过 keycloak 将 orcid id 获取到我的应用程序中?
- python - Kernel Restarting : 内核似乎已经死机。它会自动重启
- css - 如何消除渲染阻塞资源(app.css)?