【问题标题】:Scraping wrong table刮错表
【发布时间】:2020-05-09 00:10:48
【问题描述】:

我正在尝试将玩家的高级统计数据放到 Excel 表格中,但它正在抓取的表格是第一个表格,而不是高级统计表格。

ValueError: Length of passed values is 23, index implies 21

如果我尝试改用 id,则会收到另一个关于 tbody 的错误。

另外,我收到一个关于

的错误
lname=name.split(" ")[1]
IndexError: list index out of range. 

我认为这与列表中的“Nene”有关。有办法解决吗?

import requests
from bs4 import BeautifulSoup
playernames=['Carlos Delfino',
'Yao Ming',
'Andris Biedrins',
'Nene']

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-tablesaw-mode-exclude': 'columntoggle'}).find_next('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) 

【问题讨论】:

  • 您应该包含您收到的完整错误消息(也已格式化)。此外,似乎为了重现您的错误,不需要熊猫。因此,如果有人想帮助您,如果您提供导致问题的最少代码会更容易,因此愿意帮助您的人不必安装例如熊猫。
  • 顺便说一句,通过附加来创建 DataFrame 是一个坏主意,而且很少需要。 df.to_csv() 的缩进级别是否错误?
  • 我正在尝试重构您的代码,您希望从该站点获取哪些数据?
  • 我正在尝试获取每个球员的国际高级统计数据,并将他们的姓名放在每行旁边的第一列中的 Excel 表格中
  • @J.Doe 你想把所有玩家组合在一起,对吗?

标签: python pandas beautifulsoup


【解决方案1】:

巴西人只用一个名字来称呼足球,比如 Fred。如果您想使用他们的绰号(Nene/Fred),那么您需要为此实现异常处理,例如

try:
    lname=name.split(" ")[1]
except IndexError:
    lname=name

对于您的抓取问题,请尝试使用 find_all 而不是 find,这将为您提供给定页面上的每个数据表,然后您可以从列表中拉出正确的表

table = soup.find('table', attrs={'class': 'tablesaw', 'data-tablesaw-mode-exclude': 'columntoggle'}, {'id':'table-3554'}) 更改为find_all

仅供参考,每次刷新页面时表 ID 都会更改,因此您不能使用 ID 作为搜索机制。

【讨论】:

  • 名称问题似乎已解决,但我意识到我忘记更改“table =”行。我把它改回来了。 id 不应该在那里。但是,我尝试使用 find_all,但它对我不起作用
  • 我得到的错误是AttributeError: ResultSet object has no attribute 'find_all'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?
  • Find_all 会返回一个列表,table = soup.find('table', attrs={'class': 'tablesaw', 'data-tablesaw-mode-exclude': 'columntoggle'})[somenumber] 会让你找出哪个表是高级统计表...然后你可以在上面调用.find_next('tbody')
  • so table = (soup.find('table', attrs={'class': 'tablesaw', 'data-tablesaw-mode-exclude': 'columntoggle'})[somenumber]) .find_next('tbody') ?得到一个关键错误。我也只算表吗?
  • 无需深入研究机制,是的.....您还可以实现更细微的逻辑来仅查找高级统计表。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-17
  • 2019-08-07
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 2016-11-29
相关资源
最近更新 更多