首页 > 解决方案 > 尝试将抓取的数据添加到列表时仅返回一个值,Python

问题描述

我正在尝试从网站上抓取数据,我的代码的第一部分似乎有效。但是,当我尝试将该数据添加到列表中时,它仅从抓取的数据中返回一个值。我想也许它被识别为字符串,尝试了分隔符,但没有用。请帮忙!

我使用了 Goodgle Colab

提前致谢!

import requests
from bs4 import BeautifulSoup
url = "https://athletics.baruch.cuny.edu/sports/mens-swimming-and-diving/roster"
page = requests.get(url)

page.content  ##content of classes, for the problem we need "sidearm-roster-player-height" class
soup = BeautifulSoup(page.content, "html.parser")
height_swimmers = soup.findAll('span', class_ = 'sidearm-roster-player-height')
print(height_swimmers)

for text in height_swimmers:
  height = text.get_text()
  print(height)
height_list = []
height_list.append(height)

print(height_list)

标签: pythonweb-scraping

解决方案


在 for 循环之后,您只需添加heightto的最后一个值height_list

为了在列表中打印所有抓取的结果,请使用

height_list = []

for text in height_swimmers:
    height = text.get_text()
    print(height)
    height_list.append(height)

代替

for text in height_swimmers:
    height = text.get_text()
    print(height)
height_list = []
height_list.append(height)

推荐阅读