属性错误:'NoneType'对象没有属性'text' |美汤


import requests
from bs4 import BeautifulSoup
from requests_html import HTMLSession
#Request URL
page = requests.get('https://www.fifa.com/worldcup/players.html')
#Fetch webpage
soup = BeautifulSoup(page.content,"html.parser")  
player_age = soup.find("div",{"class":"fi-p__profile number__number"}).text.replace("n","").strip()
print(player_age)

错误:

属性

错误:"NoneType"对象没有属性"text">

啊好的。明白了。您的网址错误。首先,您需要删除.html。其次,您需要找到可以实际获取数据的URL。不幸的是,没有 API 端点(我可以在这里看到(来获取玩家数据。

因此,略有不同的方法是访问每个玩家的个人资料并以这种方式拉动它。但是为了访问玩家个人资料,您需要玩家 ID 进行迭代。这将需要一段时间才能运行,因为它需要从每个玩家个人资料/url中提取,但可以完成工作:

import requests
from bs4 import BeautifulSoup
from requests_html import HTMLSession
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36'}
#Get playerIDs
url = 'https://www.fifa.com/worldcup/players/_libraries/byposition/all/_players-list'
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.text,"html.parser")  
playerIDs = soup.find_all('a', {'class':'fi-p--link '})
playerDict = {}
for player in playerIDs:
name = player.find('div',{'class':'fi-p__name'}).text.strip()
playerID = player['data-player-id']
playerDict[name] = playerID

for player_name, playerID in playerDict.items():
#Request URL
url = 'https://www.fifa.com/worldcup/_libraries/players/player/%s/_player-profile-data' %playerID
page = requests.get(url, headers=headers)
#Fetch webpage
soup = BeautifulSoup(page.text,"html.parser")  
player_age = soup.find('div',{'class':'fi-p__profile-number__number'}).text.strip()
print('%-20s Age: %s' %(player_name, player_age))

输出:

Aaron MOOY           Age: 29
ABDALLA SAID         Age: 34
Abdiel ARROYO        Age: 26
Abdoulaye DIALLO     Age: 27
ABDULLAH ALKHAIBARI  Age: 23
ABDULLAH ALMUAIOUF   Age: 33
ABDULLAH OTAYF       Age: 27
Abdullahi SHEHU      Age: 26
ABDULMALEK ALKHAIBRI Age: 33
Abel AGUILAR         Age: 35
Achraf HAKIMI        Age: 21
Adama MBENGUE        Age: 26
Adem LJAJIC          Age: 28
Adil RAMI            Age: 34
Adnan JANUZAJ        Age: 25
Adolfo MACHADO       Age: 34
ADRIEN SILVA         Age: 30
AHMED ELMOHAMADY     Age: 32
AHMED FATHI          Age: 35
...

错误告诉我们soup.find("div",{"class":"fi-p__profile number__number"})什么也没找到。任何内容(None 或 NoneType(都不能具有任何属性。

顺便说一下,您提供的链接返回 404 错误。似乎您尝试在没有请求数据的情况下解析页面。

相关内容

  • 没有找到相关文章

最新更新