2015-12-21 17 views
1

我試圖從HTML數據中提取數字,以便我可以得到它們的總和。但是,當我嘗試運行它時,我遇到了上述錯誤。它是指「數據=」行。這行代碼中提到的這個錯誤是什麼?我是否正確設置了「for」循環?謝謝你的想法。TypeError:'NoneType'對象不可調用(Python:從HTML數據中刮除)

import urllib 
from bs4 import BeautifulSoup 

url = "http://python-data.dr-chuck.net/comments_42.html" 
html = urllib.urlopen(url).read() 

soup = BeautifulSoup(html, "html.parser") 
tags = soup('span') 
data = soup.findall("span", {"Comments":"Comments"}) 
numbers = [d.text for d in data] 

summation = 0 
for tag in tags: 
    print tags 
    y= tag.finall("span").text  
    summation = summation + int(y)     
print summation 

這是HTML數據的樣子:所有的

<tr><td>Modu</td><td><span class="comments">90</span></td></tr> 
<tr><td>Kenzie</td><td><span class="comments">88</span></td></tr> 
<tr><td>Hubert</td><td><span class="comments">87</span></td></tr> 

回答

1

首先,沒有findall()方法BeautifulSoup - 有find_all()。此外,你基本上是尋找元素具有Comments屬性具有Comments值:

soup.findall("span", {"Comments":"Comments"}) 

而且,這是Python的,你可以總結與built-in sum()容易得多。

修正版本:

data = soup.find_all("span", {"class": "comments"}) 
print sum(int(d.text) for d in data) # prints 2482 
+0

你是對的;我的意思是讓下劃線找到所有的方法並使用內置的sum函數。我想我的一部分習慣於經常使用「for」循環。感謝您的反饋意見。 – cybernerd