这是迄今为止我的代码:
from bs4 import BeautifulSoup
from urllib.request import urlopen
url = urlopen("http://sports.yahoo.com/nhl/scoreboard?d=2013-04-01")
content = url.read()
soup = BeautifulSoup(content)
print (soup.prettify)
table = soup.find('table')
rows = table.findAll('tr')
for tr in rows:
cols = tr.findAll('td')
for td in cols:
text = td.findAll('yspscores')
for yspscores in td:
print (yspscores)
我遇到的问题是该 yahoo 页面的 HTML 具有以下上下文中的表数据:<td class="yspscores">
我不太明白如何在我的代码中引用它。我的目标是打印出分数以及分数对应的球队名称。
您抓取了第一个表格,但该页面上有多个表格。事实上,有 46 个表。
您想要查找具有 scores
类的表:
for table in soup.find_all('table', class_='scores'):
for row in table.find_all('tr'):
for cell in row.find_all('td', class_='yspscores'):
print(cell.text)
请注意,搜索特定类是通过 class_
关键字参数完成的。
我是一名优秀的程序员,十分优秀!