2011-04-26 93 views
2

我试图解析http://www.ted.com/talks页会谈的所有名称。使用BeautifulSoup,这里是我有:故障排除AttributeError的:“结果集”对象有没有属性“的findAll”

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' 

我在做什么错?

回答

3

linkTag对象,你需要遍历集合。例如:

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

这提供了以下错误:打印[ '标题' ] NameError:名称 'A' 没有定义 – EGP 2011-04-26 22:41:31

+0

@Adam遗憾,这是一个错字。现在修复。 – interjay 2011-04-26 22:42:53

+0

看起来很迷人。谢谢!了解我可以在哪里了解更多关于'锚'的语法?举例来说:假设我想要的而不是标签。我只想改变的findAll(“IMG”?只是好奇,了解更多信息。 – EGP 2011-04-26 23:55:40

0

通过比较的方式,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 
+0

感谢额外的观点:) – EGP 2011-04-26 23:54:00

相关问题