首页 > 解决方案 > 使用.find的Python错误中的BeautifulSoup

问题描述

我知道这可能是一个简单的问题,但我真的需要帮助。

我试图从这个汤对象中提取每场比赛的总篮板数。

我尝试使用以下代码,但出现错误:

import urllib.request
from bs4 import BeautifulSoup
import csv

url = "https://www.basketball-reference.com/players/a/abdulza01.html" 
request = urllib.request.Request(url) # create request object
response = urllib.request.urlopen(request) 
html = response.read().decode('unicode_escape') # convert to unicode format
soup = BeautifulSoup(html, "html.parser")    
table = soup.find('table', attrs={'id': 'per_game'})
results = table.find_all('tr')
for result in results[1:len(results)]:
    data = result.find_all('td')
data.find(attrs={'data-stat': 'trb_per_g'}).getText()  
data = [<td class="center iz" data-stat="age"></td>,
     <td class="left " data-stat="team_id"><a href="/teams/BOS/">BOS</a></td>,
     <td class="left " data-stat="lg_id">NBA</td>,
     <td class="center iz" data-stat="pos"></td>,
     <td class="right " data-stat="g">2</td>,
     <td class="right incomplete iz" data-stat="gs"></td>,
     <td class="right " data-stat="mp_per_g">12.0</td>,
     <td class="right " data-stat="fg_per_g">1.5</td>,
     <td class="right " data-stat="fga_per_g">6.5</td>,
     <td class="right " data-stat="fg_pct">.231</td>,
     <td class="right " data-stat="ft_per_g">1.0</td>,
     <td class="right " data-stat="fta_per_g">1.5</td>,
     <td class="right " data-stat="ft_pct">.667</td>,
     <td class="right " data-stat="orb_per_g">3.0</td>,
     <td class="right " data-stat="drb_per_g">4.5</td>,
     <td class="right " data-stat="trb_per_g">**7.5**</td>,
     <td class="right " data-stat="ast_per_g">1.5</td>,
     <td class="right " data-stat="stl_per_g">0.5</td>,
     <td class="right " data-stat="blk_per_g">0.5</td>,
     <td class="right " data-stat="tov_per_g">1.5</td>,
     <td class="right " data-stat="pf_per_g">2.0</td>,
     <td class="right " data-stat="pts_per_g">4.0</td>]

错误消息:AttributeError:ResultSet 对象没有属性“find”。您可能将项目列表视为单个项目。当您打算调用 find() 时,您是否调用了 find_all()?

代码在概念上是否有问题?

标签: pythonweb-scrapingbeautifulsoup

解决方案


我认为这是您问题的答案:Beautiful Soup: 'ResultSet' object has no attribute 'find_all'?

ResultSet 对象没有“查找”属性。您可以做的是访问每个元素并使用“查找”来查找您想要的内容。


推荐阅读