用 BeautifulSoup 抢到某个 <td> class
Grabbing a certain <td> class with BeautifulSoup
尝试编写一些代码,首先将玩家的名字与他的 salary.request 相匹配。我能够编写它,以便通过从 class "sortcell" 调用它来从给定的团队中获取每个球员的名字,但我似乎无法弄清楚如何获得薪水,因为他们都叫。
from bs4 import BeautifulSoup
from urllib import urlopen
teams = ['http://espn.go.com/nba/team/roster/_/name/atl/atlanta-hawks']
for team in teams:
html = urlopen('' + team)
soup = BeautifulSoup(html.read(), 'lxml')
names = soup.findAll("td", {"class": "sortcell"})
salary = soup.findAll("td", {"class": "td"})
print(salary)
for i in range(1, 15):
name = names[i].get_text()
print(name)
你可以在以 'salary.' 开头的代码中看到我的(失败的)尝试 关于如何仅获取薪水 class 的任何想法?谢谢!
预期行为:
Salary 变量应该 return 给定球员的薪水,但目前 return 什么都没有。
你的salary
列表是空的,因为有工资信息的<td>
元素没有CSS类;当然不是 td
.
如果您从 names
单元格导航到相应的工资单元格,您的时间会更轻松;行中的最后一个:
for name in soup.find_all("td", class_="sortcell"):
salary = name.parent.find_all('td')[-1] # last cell in the row
print(name.get_text())
print(salary.get_text())
我使用了 soup.find_all()
语法; findAll()
是该方法的旧 BeautifulSoup 3 名称,已弃用。
尝试编写一些代码,首先将玩家的名字与他的 salary.request 相匹配。我能够编写它,以便通过从 class "sortcell" 调用它来从给定的团队中获取每个球员的名字,但我似乎无法弄清楚如何获得薪水,因为他们都叫。
from bs4 import BeautifulSoup
from urllib import urlopen
teams = ['http://espn.go.com/nba/team/roster/_/name/atl/atlanta-hawks']
for team in teams:
html = urlopen('' + team)
soup = BeautifulSoup(html.read(), 'lxml')
names = soup.findAll("td", {"class": "sortcell"})
salary = soup.findAll("td", {"class": "td"})
print(salary)
for i in range(1, 15):
name = names[i].get_text()
print(name)
你可以在以 'salary.' 开头的代码中看到我的(失败的)尝试 关于如何仅获取薪水 class 的任何想法?谢谢!
预期行为:
Salary 变量应该 return 给定球员的薪水,但目前 return 什么都没有。
你的salary
列表是空的,因为有工资信息的<td>
元素没有CSS类;当然不是 td
.
如果您从 names
单元格导航到相应的工资单元格,您的时间会更轻松;行中的最后一个:
for name in soup.find_all("td", class_="sortcell"):
salary = name.parent.find_all('td')[-1] # last cell in the row
print(name.get_text())
print(salary.get_text())
我使用了 soup.find_all()
语法; findAll()
是该方法的旧 BeautifulSoup 3 名称,已弃用。