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