首页 > 解决方案 > 使用 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 没有成功。还有其他方法可以做到这一点吗?

标签: pythonbeautifulsoup

解决方案


首先找到该表并用于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']

图片: 在此处输入图像描述


推荐阅读