【发布时间】:2018-10-24 18:51:38
【问题描述】:
我刚刚开始学习如何使用 Beautiful Soup。
作为练习,我选择了this page from ESPN。
那里有一张桌子,上面有 NBA 球员和他们的幻想排名。 我能够打印出整行,它显示了我在浏览器中看到的所有内容。
但是,当我自己打印每个单元格时,它会打印出“无”,因为由于某种原因,它无法解析包含锚点的单元格
下面是我的代码:
from bs4 import BeautifulSoup
import urllib2
import re
if __name__ == '__main__':
url = "http://www.espn.com/espn/print?id=20443164"
resp = urllib2.urlopen(url)
soup = BeautifulSoup(resp.read())
table = soup.find_all("table")
mytable = table[2]
rows = mytable.findChildren(['th','tr'])
print rows
for row in rows:
cells = row.findChildren('td')
for cell in cells:
# print cell.string # line in question
print cell # line in question
如果我使用
print cell
我得到以下输出:
<td>1. <a href="http://www.espn.com/nba/player/_/id/3032977/giannis-antetokounmpo">Giannis Antetokounmpo</a>, SF/PF</td>
<td>PHI</td>
<td>C24</td>
如果我使用
print cell.string
我得到以下输出:
None
MIL
SF1
那么我怎样才能在没有“td”标签的情况下打印所有内容,但在不打印“None”的情况下识别第一个单元格中的所有内容?
【问题讨论】:
标签: python python-2.7 beautifulsoup