【问题标题】:How to access span using beautifulSoup?如何使用 beautifulSoup 访问跨度?
【发布时间】:2013-07-26 22:39:12
【问题描述】:

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

我的代码输出了这个,但我想得到 #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

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    访问嵌套跨度的文本:

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

    您需要确保row.find("span", 'rankings-score') 确实找到了一些东西;上面我测试有确实找到了&lt;span&gt;

    如果没有找到匹配的对象,.find() 方法会返回None,所以一般来说,每当你得到一个AttributeError: 'NoneType' object has no attribute ... 异常,涉及你试图用Element.find() 加载的对象,那么你需要测试None之前试图进一步访问信息。

    这适用于object.findobject.find_allobject[...]标签属性访问、object.&lt;tagname&gt;object.select等。

    【讨论】:

    • 击败我...我要补充一点,可能需要class_='rankings-score'或同等学历...目前可能更多的是侥幸...
    • 所以我之前尝试过,但只是说:row.find('span', 'rankings-score').find('span').text 并得到一个 AttributeError: 'NoneType ' 对象没有属性 'contents'
    • @goldisfine:有些行没有有这样的&lt;span class="rankings-score"&gt;
    • 那么'class_' 与'class' 是什么关系呢? 'class' 是 python 保护词还是什么,所以 BS 使用 class_
    • 没错。 class 是保留字(用于定义类),因此您不能将其用作关键字参数。
    猜你喜欢
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2015-09-05
    • 2021-10-05
    • 2022-06-27
    • 1970-01-01
    • 2022-12-06
    相关资源
    最近更新 更多