2014-02-11 56 views
2

我遇到了一個奇怪的錯誤。我試圖做一些基本的解析。從本質上講,我以'x'格式收集數據,並希望以我可以使用的格式返回所有內容。我的直接問題是我的代碼返回了一個奇怪的錯誤。我已經瀏覽了一些關於同一問題的其他帖子/答案,但是出於上下文的考慮......確實難以確定問題。TypeError:'NoneType'對象不可調用,BeautifulSoup

data = url.text 

soup = BeautifulSoup(data, "html5lib") 

results = [] # this is what my result set will end up as 

def parseDiv(text): 
    #function takes one input parameter - a single div for which it will parse for specific items, and return it all as a dictionary 
    soup2 = BeautifulSoup(text) 
    title = soup2.find("a", "yschttl spt") 
    print title.text 
    print 

    return title.text 

for result in soup.find_all("div", "res"): 
    """ 
    This is where the data is first handled - this would return a div with links, text, etc - 
    So, I pass the blurb of text into the parseDiv() function 
    """ 
    item = parseDiv(result) 
    results.append(item) 
在這一點上

很顯然,我已經包括了我所需要的庫......當我拉了soup2代碼(BS4的第二個實例在我的文字要處理的新導語),而只打印我的功能的輸入,這一切工作。

以下是錯誤:

Traceback (most recent call last): 
    File "testdata.py", line 29, in <module> 
    item = parseDiv(result) 
    File "testdata.py", line 17, in parseDiv 
    soup2 = BeautifulSoup(text) 
    File "C:\Python27\lib\site-packages\bs4\__i 
    markup = markup.read() 
TypeError: 'NoneType' object is not callable 
+1

請發佈完整的錯誤堆棧跟蹤。 – thefourtheye

+1

「但是出於上下文...確實難以確定問題」 - 這同樣適用於不完整的回溯。你能包括所有的行嗎? – mhlester

+0

編輯顯示堆棧跟蹤。 – Alpinestar22

回答

4

你不需要再次解析的div。試試這個:

for div in soup.find_all('div', 'res'): 
    a = div.find('a', 'yschttl spt') 
    if a: 
     print a.text 
     print 
     results.append(a) 
+0

謝謝@Jayanth,這減輕了一個問題,但現在我收到一個屬性錯誤:Traceback(最近調用最後一次): 文件「testdata.py」,行24,在 項目['title'] = a.text AttributeError:'NoneType'對象沒有屬性'text' – Alpinestar22

+0

@ Alpinestar22然後顯然有東西返回'None',你應該檢查它。 – glglgl

+0

@ Alpinestar22:如果其中一個'div'沒有類'yschttl spt'的'a',就會發生這種情況。 –