首页 > 解决方案 > Beautiful Soup 只返回表格的最后一个值

问题描述

我正在尝试从PGA 统计网站上的此页面中抓取表格数据。我正在获取玩家姓名,代码似乎可以正常工作,但它只返回站点的最后一个值“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

标签: pythonweb-scrapingbeautifulsouphtml-table

解决方案


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

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)

推荐阅读