【问题标题】:AttributeError: 'NoneType' object has no attribute 'tbody'AttributeError:“NoneType”对象没有属性“tbody”
【发布时间】:2020-01-22 17:10:09
【问题描述】:

我正在尝试创建一个包含球员统计数据的 Excel 表格,但是当我尝试抓取特定表格时,我不断得到

AttributeError:“NoneType”对象没有属性“tbody”。

在这种情况下,我想要 Excel 表上列出的球员的高级统计表。如果不存在高级统计信息,请将名称旁边的行留空。

import requests
import pandas as pd
from bs4 import BeautifulSoup
playernames=['Dominique Jones', 'Joe Young', 'Darius Adams', 'Lester Hudson', 'Marcus Denmon', 'Courtney Fortson']

for name in playernames:
  fname=name.split(" ")[0]
  lname=name.split(" ")[1]
  url="https://basketball.realgm.com/search?q={}+{}".format(fname,lname)
  response = requests.get(url)

  soup = BeautifulSoup(response.content, 'html.parser')
  table = soup.find('table', attrs={'class':'tablesaw', 'data-table-saw-mode-exclude':'columntoggle'}).tbody
  print(table)  

  columns = ['Season', 'Team', 'League', 'GP', 'GS', 'TS%', 'eFG%', 'ORB%', 'DRB%', 'TRB%', 'AST%', 'TOV%', 'STL%', 'BLK%', 'USG%', 'Total S%', 'PPR', 'PPS', 'ORtg', 'DRtg', 'PER']
df = pd.DataFrame(columns=columns)


  trs = table.find_all('tr')
  for tr in trs:
    tds = tr.find_all('td')
    row = [td.text.replace('\n', '') for td in tds]
    df = df.append(pd.Series(row, index=columns), ignore_index=True)

df.to_csv('international players.csv', index=False) 

【问题讨论】:

  • 似乎有一个您没有考虑过的案例?您确定https://basketball.realgm.com/search?q=Dominique+Jones 是您要抓取的网址之一吗?如果您查看网页,它不会显示您要查找的列。我认为有一种情况你没有考虑过,如果搜索返回多个玩家,它不会在该页面上显示他们的统计数据。

标签: python pandas beautifulsoup python-requests


【解决方案1】:

我认为您提供了错误的属性名称。这应该是data-tablesaw-mode-exclude 不是 data-table-saw-mode-exclude

改变这个

table = soup.find('table', attrs={'class':'tablesaw', 'data-table-saw-mode-exclude':'columntoggle'}).tbody

到这里

table = soup.find('table', attrs={'class': 'tablesaw', 'data-tablesaw-mode-exclude': 'columntoggle'}).find_next('tbody')

【讨论】:

  • 这有效,但为什么我得到 ValueError:传递值的长度是 23,索引意味着 21?我数了好几遍,我认为我猜对了。
  • 对不起,我离开了一天。我明天会回来。同时尝试一些研究。
【解决方案2】:

在您创建soup.find(.... 的行中,您正在寻找data-table-saw-mode-exclude 属性,但它必须是data-tablesaw-mode-exclude

【讨论】:

    猜你喜欢
    • 2019-03-07
    • 2019-01-01
    • 2021-12-26
    • 2019-07-23
    • 2018-05-13
    • 2020-09-07
    • 2017-05-03
    • 2023-03-16
    • 2018-07-14
    相关资源
    最近更新 更多