2011-05-03 69 views
0

得到以下错误:BeautifulSoup错误(CGI逃亡)

Traceback (most recent call last):
File "stack.py", line 31, in ?
print >> out, "%s" % escape(p) File
"/usr/lib/python2.4/cgi.py", line
1039, in escape
s = s.replace("&", "&") # Must be done first! TypeError: 'NoneType'
object is not callable

对于下面的代码:

import urllib2 
from cgi import escape # Important! 
from BeautifulSoup import BeautifulSoup 

def is_talk_anchor(tag): 
return tag.name == "a" and tag.findParent("dt", "thumbnail") 

def talk_description(tag): 
return tag.name == "p" and tag.findParent("h3") 

links = [] 
desc = [] 

for pagenum in xrange(1, 5): 
soup = BeautifulSoup(urllib2.urlopen("http://www.ted.com/talks?page=%d" % pagenum)) 
links.extend(soup.findAll(is_talk_anchor)) 
page = BeautifulSoup(urllib2.urlopen("http://www.ted.com/talks/arvind_gupta_turning_trash_into_toys_for_learning.html")) 
desc.extend(soup.findAll(talk_description)) 

out = open("test.html", "w") 

print >>out, """<html><head><title>TED Talks Index</title></head> 
<body> 
<table> 
<tr><th>#</th><th>Name</th><th>URL</th><th>Description</th></tr>""" 

for x, a in enumerate(links): 
    print >> out, "<tr><td>%d</td><td>%s</td><td>http://www.ted.com%s</td>" % (x + 1, escape(a["title"]), escape(a["href"])) 

for y, p in enumerate(page): 
    print >> out, "<td>%s</td>" % escape(p) 

print >>out, "</tr></table>"                  

我认为这个问题是% escape(p)。我试图把<p>的内容拿出来。我不应该使用逃脱?

还分别具有与行的问题:

page = BeautifulSoup(urllib2.urlopen("%s") % a["href"]) 

这就是我想做的事,但同样运行到错误并想知道是否有这样做的另一种方式。试图收集我从前面的代码中找到的链接,并再次通过BeautifulSoup运行它。

+0

你的缩进搞砸了吧? – 2011-05-03 04:59:41

回答

1

您必须调查(使用pdb)为什么您的一个链接返回为None实例。

特别是:追踪是自我说话。 escape()被调用None。因此,您必须调查哪些参数是无......这是“链接”中的项目之一。那么为什么你的一个项目没有?

很可能是因为您的通话之一

def is_talk_anchor(tag): 
    return tag.name == "a" and tag.findParent("dt", "thumbnail") 

回报无因tag.findParent( “DT”, “缩略图”)返回无(由于您指定的HTML输入)。

因此,您必须检查或过滤“连接”中的项目为无(或调整上面的解析器代码)以便根据您的需要仅拾取现有链接。

请仔细阅读您的回溯并思考问题可能是什么 - 回溯是非常有用的,并为您提供有关您问题的宝贵信息。