Im新的python和我的代码如下:我有一个爬虫,在新发现的链接上递归。在根链接上递归之后,似乎程序在打印几条链接后停止,这应该继续一段时间,但不是。我正在捕捉和打印异常,但程序终止成功,所以我不知道为什么它会停止。为什么这个递归停止
from urllib import urlopen
from bs4 import BeautifulSoup
def crawl(url, seen):
try:
if any(url in s for s in seen):
return 0
html = urlopen(url).read()
soup = BeautifulSoup(html)
for tag in soup.findAll('a', href=True):
str = tag['href']
if 'http' in str:
print tag['href']
seen.append(str)
print "--------------"
crawl(str, seen)
except Exception, e:
print e
return 0
def main():
print "$ = " , crawl("http://news.google.ca", [])
if __name__ == "__main__":
main()
尝试记录您为每个请求收到的html。也许有些网站由于缺少用户代理或其他缺少http头部而给你空白结果?此外,href可能不包含协议(http或https),这意味着您将跳过它。 – Steve 2012-07-28 09:21:03