【问题标题】:Beautiful Soup only returns last value of tableBeautiful Soup 只返回表格的最后一个值
【发布时间】:2020-12-16 13:57:46
【问题描述】:

我正在尝试从 PGA 统计网站上的this page抓取表格数据。我正在获取玩家姓名,代码似乎可以正常工作,但它只返回站点的最后一个值“Patrick Rodgers”。我在这里做错了什么?

这是它正在抓取的html

这是我的源代码:

#Get URL and Parse
url = 'https://www.pgatour.com/content/pgatour/stats/stat.02674.y2020.eon.t027.html'
results = requests.get(url)
soup = BeautifulSoup(results.text, 'html.parser')

#Find data
sg_ttg = soup.find('table', id = 'statsTable')

#Get data
for player in sg_ttg.find_all('tbody'):
    rows = player.find_all('tr')
    for row in rows:
        playername = row.find('td', class_= 'player-name').text

【问题讨论】:

  • 您在最后 2 个 for 循环中使用了相同的变量名来处理 2 个事情。
  • 我在发帖后就注意到了,所以我将变量改为 player_nm 而不是 player = row.find...,但它仍然只返回最后一个值。
  • 您如何存储数据。当您执行print('playername') 时,会出现“Patrick Rodgers”
  • 只需运行您的代码,为我打印每个名称。 repl.it/@jimtje/BriefVirtuousRefactoring

标签: python web-scraping beautifulsoup html-table


【解决方案1】:

要获取所有数据,请尝试定义列表并附加每个值:

players = []
for table in sg_ttg.find_all('tbody'):
    rows = table.find_all('tr')
    for row in rows:
        player = row.find('td', class_= 'player-name').text.strip()
        players.append(player)

print(players)

【讨论】:

  • 这很好,谢谢!但是,现在它正在获取名称前后带有 '\n 的名称。如果这是一个愚蠢的问题,我是 Python 新手,很抱歉,但我该如何删除它?
猜你喜欢
  • 1970-01-01
  • 2020-07-27
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多