如何使用beautifulSoup访问span?

时间:2013-07-26 15:15:58

标签: python beautifulsoup

我想获取嵌套标记中的数字。我该怎么做?

我的代码输出了这个,但我想得到#40,而不是整行两行:

<span class="rankings-score">
<span>#40</span>

这是我的代码:

from bs4 import BeautifulSoup
import requests
import csv

site =  "http://www.usnews.com/education/best-high-schools/national-rankings/page+2"

fields = ['national_rank','school','address','school_page','medal','ratio','size_desc','students','teachers'] 

r = requests.get(site)
html_source = r.text
soup = BeautifulSoup(html_source)

table = soup.find('table')    
rows_list = []      

for row in table.find_all('tr'):                                                                                                                                                                                                                                               

    d = dict()

    d['national_rank'] = row.find("span", 'rankings-score')
    print d['national_rank']

我收到此错误:

AttributeError: 'NoneType' object has no attribute 'span'

当我尝试这个时:

d['national_rank'] = row.find("span", 'rankings-score').span.text

1 个答案:

答案 0 :(得分:5)

访问嵌套范围的文本:

score_span = row.find("span", 'rankings-score')
if score_span is not None:
    print score_span.span.text

您需要确保row.find("span", 'rankings-score')确实找到了某些内容;上面我测试 确实找到了<span>

如果找不到匹配的对象,.find()方法会返回None,因此通常情况下,每当遇到AttributeError: 'NoneType' object has no attribute ...异常时,涉及您尝试使用{{1}加载的对象然后,您需要在尝试进一步访问信息之前测试Element.find()

这适用于Noneobject.findobject.find_all代码属性访问权限,object[...]object.<tagname>等。