【问题标题】:Troubleshooting AttributeError: 'ResultSet' object has no attribute 'findAll'AttributeError 疑难解答:“ResultSet”对象没有属性“findAll”
【发布时间】:2011-04-26 22:28:08
【问题描述】:

我正在尝试解析http://www.ted.com/talks 页面中的所有谈话名称。使用 BeautifulSoup,这就是我所拥有的:

import urllib2

from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen("http://www.ted.com/talks")

soup = BeautifulSoup(page)

link = soup.findAll(lambda tag: tag.name == 'a' and tag.findParent('dt', 'thumbnail'))

for anchor in link.findAll('a', title = True):
    print anchor['title']

最初的“链接”显示了一个很好的数组,其中包含八个视频块。然后我尝试通过这个并取出标签中的标题,使用上面的代码,这给了我以下错误:

for anchor in link.findAll('a', title=True):
AttributeError: 'ResultSet' object has no attribute 'findAll'

我做错了什么?

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    linkTag 对象的集合,您需要对其进行迭代。例如:

    for anchor in link:
        print anchor['title']
    

    【讨论】:

    【解决方案2】:

    通过比较,pyparsing 方法看起来像这样:

    from contextlib import closing
    import urllib2
    from pyparsing import makeHTMLTags, withAttribute
    
    # pull HTML from web page
    with closing(urllib2.urlopen("http://www.ted.com/talks")) as page:
        html = page.read()
    
    # define opening and closing tags
    dt,dtEnd = makeHTMLTags("dt")
    a,aEnd = makeHTMLTags("a")
    
    # restrict <dt> tag matches to those with class='thumbnail'
    dt.setParseAction(withAttribute(**{'class':'thumbnail'}))
    
    # define pattern of <dt> tag followed immediately by <a> tag
    patt =  dt + a("A")
    
    # scan input html for matches of this pattern, and access
    # attributes of the <A> tag
    for match,s,e in patt.scanString(html):
        print match.A.title
        print match.A.href
        print
    

    给予:

    Bruce Schneier: The security mirage
    /talks/bruce_schneier.html
    
    Harvey Fineberg: Are we ready for neo-evolution?
    /talks/harvey_fineberg_are_we_ready_for_neo_evolution.html
    
    Ric Elias: 3 things I learned while my plane crashed
    /talks/ric_elias.html
    
    Anil Ananthaswamy: What it takes to do extreme astrophysics
    /talks/anil_ananthaswamy.html
    
    John Hunter on the World Peace Game
    /talks/john_hunter_on_the_world_peace_game.html
    
    Kathryn Schulz: On being wrong
    /talks/kathryn_schulz_on_being_wrong.html
    
    Sam Richards: A radical experiment in empathy
    /talks/sam_richards_a_radical_experiment_in_empathy.html
    
    Susan Lim: Transplant cells, not organs
    /talks/susan_lim.html
    
    Marcin Jakubowski: Open-sourced blueprints for civilization
    /talks/marcin_jakubowski.html
    
    Roger Ebert: Remaking my voice
    /talks/roger_ebert_remaking_my_voice.html
    

    【讨论】:

    • 感谢您提供额外的视角 :)
    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 2013-08-06
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    相关资源
    最近更新 更多