2012-12-01 302 views
1

我在python下面編寫了一個非常簡單的網絡爬蟲程序,但是當我運行它時,它返回我 'NoneType'對象不可調用',你能幫我嗎?簡單的網絡爬蟲

import BeautifulSoup 
import urllib2 
def union(p,q): 
    for e in q: 
     if e not in p: 
      p.append(e) 

def crawler(SeedUrl): 
    tocrawl=[SeedUrl] 
    crawled=[] 
    while tocrawl: 
     page=tocrawl.pop() 
     pagesource=urllib2.urlopen(page) 
     s=pagesource.read() 
     soup=BeautifulSoup.BeautifulSoup(s) 
     links=soup('a')   
     if page not in crawled: 
      union(tocrawl,links) 
      crawled.append(page) 

    return crawled 
crawler('http://www.princeton.edu/main/') 
+1

您可以發佈完整回溯?這應該至少縮小「None」值的函數調用的範圍。 – Blckknght

回答

5

[更新]下面是完整的項目代碼

https://bitbucket.org/deshan/simple-web-crawler

[ANWSER]

湯( 'A')返回完整的HTML標籤。

<a href="http://itunes.apple.com/us/store">Buy Music Now</a> 

所以的urlopen給出了錯誤 'NoneType' 對象不是可調用」。你需要提取唯一的url/href。

links=soup.findAll('a',href=True) 
for l in links: 
    print(l['href']) 

您需要的URL too.refer驗證到以下anwsers

我再次想建議你使用Python設置而不是Arrays.you可以輕鬆地添加,省略重複的你LS。

試試下面的代碼:

import re 
import httplib 
import urllib2 
from urlparse import urlparse 
import BeautifulSoup 

regex = re.compile(
     r'^(?:http|ftp)s?://' # http:// or https:// 
     r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... 
     r'localhost|' #localhost... 
     r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip 
     r'(?::\d+)?' # optional port 
     r'(?:/?|[/?]\S+)$', re.IGNORECASE) 

def isValidUrl(url): 
    if regex.match(url) is not None: 
     return True; 
    return False 

def crawler(SeedUrl): 
    tocrawl=[SeedUrl] 
    crawled=[] 
    while tocrawl: 
     page=tocrawl.pop() 
     print 'Crawled:'+page 
     pagesource=urllib2.urlopen(page) 
     s=pagesource.read() 
     soup=BeautifulSoup.BeautifulSoup(s) 
     links=soup.findAll('a',href=True)   
     if page not in crawled: 
      for l in links: 
       if isValidUrl(l['href']): 
        tocrawl.append(l['href']) 
      crawled.append(page) 
    return crawled 
crawler('http://www.princeton.edu/main/')