我想從網站“https://www.maxifoot.fr/classement-buteur-eu??rope-annee-civile-2021.htm”中抓取資料
我試圖在 Python 上提取這些資料,但我無法做到。我想用這些資料和相同的欄位在 Python 上創建一個表。有人可以嘗試幫助我使用 Pandas、beautifulsoup... 進行資料提取的腳本嗎?
我已經試過了:
import requests
from bs4 import BeautifulSoup
import pandas as pd
url = 'https://www.maxifoot.fr/classement-buteur-europe-annee-civile-2021.htm'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'lxml')
print(soup.prettify())
for i in soup.find_all("tr"):
print(i.find_all("td"))
print ("")
colonnes = ["Nom","Equipe","Buts","Matchs joués"]
df = pd.DataFrame(columns = colonnes)
df
for i in soup.find_all("tr")[1:]:
href = i.find_all("td")
df = df.append({'Nom': href}, ignore_index=True)
print(df.head())
uj5u.com熱心網友回復:
有一種更簡單的方法來獲取資料并將其放入資料框中 -pandas.read_html如果需要,使用 pandas 進行調整。
df = pd.read_html('https://www.maxifoot.fr/classement-buteur-europe-annee-civile-2021.htm', match = 'min/but*')[1]
df['href'] = df["Joueur"].apply(lambda x: 'https://www.maxifoot.fr' soup.select_one(f'a:-soup-contains("{x}")')['href'])
如果你喜歡用 BeautifulSoup 解決它,你必須做一些調整:
...
data = []
for row in soup.select('.butd1 tr')[1:]:
strings = list(row.stripped_strings)
strings[3:5] = [''.join(strings[3:5])]
strings[6:8] = [''.join(strings[6:8])]
a = 'https://www.maxifoot.fr' row.a['href']
strings.append(a)
data.append(strings)
colonnes = ['Pos','Nom','Equipe','Buts','dontchamp.','Matchs joués','min/but*','href']
pd.DataFrame(data,columns = colonnes)
輸出
| 位置 | 名稱 | 裝備 | 布斯 | 東尚。 | 火柴 | 分鐘/但是* | href |
|---|---|---|---|---|---|---|---|
| 1. | R.萊萬多夫斯基 | 拜仁慕尼黑 | 58 (11 頁) | 43 | 47 (1,23 桶/米) | 68' | https://www.maxifoot.fr/joueur/robert-lewandowski-13191.htm |
| 2. | E. 哈蘭德 | 多特蒙德 | 43 (6 頁) | 30 | 43 (1,00 桶/米) | 85' | https://www.maxifoot.fr/joueur/erling-haland-190157.htm |
| . | K. MBAPPé | 巴黎 SG | 43 (7 頁) | 24 | 53 (0.81 桶/米) | 104' | https://www.maxifoot.fr/joueur/kylian-mbappe-lottin-183802.htm |
| 4. | K.本澤馬 | 皇家馬德里 | 38 (3 頁) | 30 | 50 (0.76 桶/米) | 109' | https://www.maxifoot.fr/joueur/karim-benzema-10476.htm |
| 5. | 穆罕默德·薩拉赫 | 利物浦 | 37 (4 頁) | 24 | 53 (0.70 桶/米) | 122' | https://www.maxifoot.fr/joueur/mohamed-salah-59580.htm |
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/401175.html
